Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch in Django for username pass to view
I'm working on a basic Django app (just learning, this is my third small project), and I'm trying to add links to allow a list of every post a user has made. I've got the URLS being created OK (domain/posts/username), and I want this to link to a view (that I've already created, and which works when the parameters I want to pass are hard-coded to a single value), passing the positional arguments to the view. However, I'm running aground on the RegEx / Urls part of things. I think this is the relevant info: urls.py: urlpatterns = [ url(r'^create/', views.create, name='create'), url(r'^(?P<pk>[0-9]+)/upvote', views.upvote, name='upvote'), url(r'^(?P<pk>[0-9]+)/downvote' , views.downvote, name='downvote'), url(r'^userposts/(?P<user>[.]+)', views.userposts, name='userposts') views.py def userposts(request,user): posts = models.Post.objects.filter(url__contains=user) return render(request, 'posts/userposts.html', {'posts': posts}) home.html a href="{{ post.url}}">{{ post.title }}</a><br/>{{ post.pub_date_pretty }} by <a href="{% url 'posts:userposts' %}{{post.author.username}}">{{ post.author.username }}</a></td> With the (?P[.]+) part of the last url line removed, the page will render OK, but the links don't work (as there's no user parameter being passed). With the regex present (not only this one, but the many others I've tried), I get a NoReverseMatch error: NoReverseMatch at / Reverse for 'userposts' with no arguments not found. 1 pattern(s) tried: ['posts/userposts/(?P<user>[.]+)'] … -
Django "python setup.py egg_info" failed with error code 1
Welcome friends I need your help. I'm a newbie in Python. Unfortunately I have ResponseError. I can not install weasyprint. I received this error traceback from the Django Shell: pip install weasyprint Collecting weasyprint Using cached WeasyPrint-0.36.tar.gz Collecting lxml>=3.0 (from weasyprint) Using cached lxml-3.7.3-cp34-cp34m-manylinux1_x86_64.whl Collecting html5lib>=0.999999999 (from weasyprint) Using cached html5lib-0.999999999-py2.py3-none-any.whl Collecting tinycss>=0.4 (from weasyprint) Using cached tinycss-0.4.tar.gz Collecting cssselect>=0.6 (from weasyprint) Using cached cssselect-1.0.1-py2.py3-none-any.whl Collecting cffi>=0.6 (from weasyprint) Using cached cffi-1.10.0-cp34-cp34m-manylinux1_x86_64.whl Collecting cairocffi>=0.5 (from weasyprint) Using cached cairocffi-0.8.0.tar.gz Complete output from command python setup.py egg_info: Installed /tmp/pip-build-lcjuxnqg/cairocffi/.eggs/cffi-1.10.0-py3.4-linux-x86_64.egg Searching for pycparser Reading https://pypi.python.org/simple/pycparser/ Downloading https://pypi.python.org/packages/be/64/1bb257ffb17d01f4a38d7ce686809a736837ad4371bcc5c42ba7a715c3ac/pycparser-2.17.tar.gz#md5=ca98dcb50bc1276f230118f6af5a40c7 Best match: pycparser 2.17 Processing pycparser-2.17.tar.gz Writing /tmp/easy_install-id3ylwwu/pycparser-2.17/setup.cfg Running pycparser-2.17/setup.py -q bdist_egg --dist-dir /tmp/easy_install-id3ylwwu/pycparser-2.17/egg-dist-tmp-njzyefi7 warning: no previously-included files matching 'yacctab.*' found under directory 'tests' warning: no previously-included files matching 'lextab.*' found under directory 'tests' warning: no previously-included files matching 'yacctab.*' found under directory 'examples' warning: no previously-included files matching 'lextab.*' found under directory 'examples' zip_safe flag not set; analyzing archive contents... pycparser.ply.__pycache__.yacc.cpython-34: module references __file__ pycparser.ply.__pycache__.yacc.cpython-34: module MAY be using inspect.getsourcefile pycparser.ply.__pycache__.yacc.cpython-34: module MAY be using inspect.stack pycparser.ply.__pycache__.lex.cpython-34: module references __file__ pycparser.ply.__pycache__.lex.cpython-34: module MAY be using inspect.getsourcefile pycparser.ply.__pycache__.ygen.cpython-34: module references __file__ creating /tmp/pip-build-lcjuxnqg/cairocffi/.eggs/pycparser-2.17-py3.4.egg Extracting pycparser-2.17-py3.4.egg to /tmp/pip-build-lcjuxnqg/cairocffi/.eggs Installed /tmp/pip-build-lcjuxnqg/cairocffi/.eggs/pycparser-2.17-py3.4.egg Traceback (most recent call last): File … -
Django can't find Webpack bundle when using React
I'm getting this error message: "GET /static/bundles/main-0dfd33c549ecc5de3a40.js HTTP/1.1" 404 1721 as I am navigating my web site on my local host. This bundle was made using webpack and DEFINITELY exists in this location. Every time i collectstatic and create a new bundle, my django recognizes that there is a new bundle but still gives me this 404 error saying that it can't GET it... I'm new to this forum and new to programming so I'm not sure if I'm being detailed enough or if there is other information I should include to help troubleshoot this.. Please let me know. Thank you! -
Error loading MySQLdb module: No module named MySQLdb AFTER virutalenv
Ok I have been pouring over this site and google but cannot find the right answer. I should start by mentioning I'm new to this stuff. I had a django project 90 percent done. I am building it in Linux with a virtualenv. For some reason when I was in the project directory I decided to type 'virualenv .' Not sure what this did, assuming it overwrote my current settings, but now everything is broke. I'm trying to fix it all. I am using python 2.7, but I am getting the following traceback: enter code here File "/root/IPNV/django-test/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/root/IPNV/django-test/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/root/IPNV/django-test/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "/root/IPNV/django-test/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/root/IPNV/django-test/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/root/IPNV/django-test/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/root/IPNV/django-test/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/root/IPNV/django-test/local/lib/python2.7/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/root/IPNV/django-test/local/lib/python2.7/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/root/IPNV/django-test/local/lib/python2.7/site-packages/django/db/models/base.py", line 124, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/root/IPNV/django-test/local/lib/python2.7/site-packages/django/db/models/base.py", line 330, in add_to_class value.contribute_to_class(cls, name) File "/root/IPNV/django-test/local/lib/python2.7/site-packages/django/db/models/options.py", line 214, in contribute_to_class self.db_table = … -
TypeError: view must be a callable or a list/tuple in the case of include(). Django/python3
I am getting this error every time I try to run my app in Django. What's happen? My urls.py This is my console -
In Django, Handling hashtag class didn't return an HttpResponse object. It returned None instead
I have started learning Django, I'm not sure how to handle HttpResponseRedirect(). Here is the code snippet of the profile.html. <form method="post" action="post/"> {% csrf_token %} <div class="col-md-8 col-md-offset-2 fieldWrapper"> {{ form.text.errors }} {{ form.text }} </div> {{ form.country.as_hidden }} <div> <input type="submit" value="post"> </div> </form> As you can see on the snippet code, when I click submit button, it goes to http://localhost:8000/user/sapphire/post/ I guess. Here is the snippet code in urls.py. from tweets.views import PostTweet urlpatterns = [ url(r'^user/(\w+)/$', Profile.as_view()), url(r'^user/(\w+)/post/$', PostTweet.as_view()), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) As you can see, when I click submit button, we navigate to the PostTweet class in views.py. Here is the snippet code in views.py. from django.shortcuts import render from django.views.generic import View from .models import Tweet from user_profile.models import User from .forms import TweetForm class PostTweet(View): def post(self, request, username): form = TweetForm(self.request.POST) if form.is_valid(): user = User.objects.get(username = username) tweet = Tweet(text = form.cleaned_data['text'], user = user, country = form.cleaned_data['country']) tweet.save() words = form.cleaned_data['text'].spilt(" ") for word in words: if word[0] == "#": hashtag, created = HashTag.objects.get_or_create(name = word[1:]) hastag.tweet.add(tweet) return HttpResponseRedirect('/user/' + username) As you can see, when I click submit button, I guess it goes to http://localhost:8000/user/sapphire/, and render another tweet … -
Passing select value to JavaScript function from Django form
In forms.py, I have defined the following: user_request_type = forms.ModelChoiceField(label='Request Type', queryset=UserRequestType.objects.all(), empty_label='Select Request Type', widget=forms.Select(attrs={'onChange':'show_hide_user_other_request_type(this.value)'})) In an HTML page, I have defined the following: <script> function show_hide_user_other_request_type(user_request_type) { if (user_request_type == 'Other') { $("#user-other-request-type").show(); } else { $("#user-other-request-type").hide(); } } </script> user_request_type is never passed. Any help would be appreciated. Thanks. -
TypeError: __init__() missing 1 required positional argument: 'to'
class Customer(models.Model): """客户信息表""" name = models.CharField(max_length=32, blank=True, null=True) qq = models.CharField(max_length=64, unique=True) qq_name = models.CharField(max_length=64, blank=True, null=True) phone = models.CharField(max_length=64, blank=True, null=True) source_choice = ((0, '转介绍'), (1, 'QQ群'), (2, '官网'), (3, '百度推广'), (4, '51CTO'), (5, '知乎'), (6, '市场推广'), ) source = models.SmallIntegerField(choices=source_choice) referral_from = models.CharField(verbose_name="转介绍人QQ", max_length=64, blank=True, null=True) consult_course = models.ForeignKey("Course", verbose_name="资讯课程") content = models.TextField(verbose_name="咨询详情") tags = models.ManyToManyField("Tag", blank=True, null=True) consultant = models.ForeignKey(verbose_name="UserProfile") memo = models.TextField(blank=True, null=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.qq class UserProfile(models.Model): """用户账户表""" user = models.OneToOneField(User) name = models.CharField(max_length=32) roles = models.ManyToManyField("Role", bank=True, null=True) def __str__(self): return self.name when i running this code(python manage.py makemigration crms) in terminal, Traceback (most recent call last): File "D:\python\CRM项目实战\CRM\crm\crms\models.py", line 26, in Customer consultant = models.ForeignKey(verbose_name="UserProfile") TypeError: init() missing 1 required positional argument: 'to'""" -
Django: DetailView get objects from foreignkey
I have a class-based DetailView for my model Event and want to show kategorie entries that are related by foreignkey. models.py class Event(models.Model): name = models.CharField(max_length=50) def get_absolute_url(self): return reverse('events:event-detail', kwargs={'pk': self.pk}) class Kategorie(models.Model): event = models.ForeignKey(Event) def get_absolute_url(self): return reverse('events:kategorie-detail', kwargs={'pk': self.pk}) views.py class EventDetail(generic.DetailView): model = Event context_object_name = 'event' event_detail.html How can I get the kategories that are related to the event? Until now I used functional views. <ul> {% for kategorie in kategorien %} <li><a href="{% url 'events:kategorie-detail' kategorie.id %}">{{kategorie}}</a></li> {% endfor %} </ul> -
COnverting from function to class inheritance cryptic error
I'm trying to change my 3 similar function views into inheritance class based views. Views look almost identically only the form and their name is different. One of them below: @login_required def add_video(request): if request.method == 'POST': movie_form = MovieForm(request.POST) if movie_form.is_valid(): user = request.user new_post = movie_form.save(commit=False) new_post.author = user new_post.save() movie_form.save_m2m() messages.success(request, 'Post successfully added') return redirect(new_post) else: movie_form = MovieForm() return render(request, 'ak47/movie.html', {'movie_form': movie_form}) As CBV it looks like this: @login_required class AddingView(CreateView): def form_valid(self, form): user = self.request.user new_post = form.save(commit=False) new_post.author = user new_post.save() form.save_m2m() messages.success(request, 'Post successfully added') class AddMovieView(AddingView): form_class = MovieForm class AddUrlView(AddingView): form_class = UrlImgForm Unfortunately error log shows something weird: File "/home/cruel/PycharmProjects/silverak/ak47/views.py", line 249, in <module> class AddMovieView(AddingView): TypeError: function() argument 1 must be code, not str -
Load image dont work in django-ckeditor?
I am tring to use django-ckeditor app to my TextField. I want to load image from computer but there is no load button. Also I cant enter url of picture. Whats wrong I did? How to fix this problem. Here below you can see want I did. 1) I add ckeditor and ckeditor_uploader to INSTALLED_APPS setting.py: 2) I run the collectstatic management command. settings.py: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root') MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH = "media/uploads/" CKEDITOR_JQUERY_URL = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js" CKEDITOR_IMAGE_BACKEND = 'pillow' models.py: class Model(models.Model): content= RichTextField(_('Description')) forms.py: class ProgramForm(forms.ModelForm): description = forms.CharField(widget=CKEditorWidget()) class Meta: model = Program fields = ('description',) template: {% load widget_tweaks %} {{ form.media }} <form method="post" action=""> {% csrf_token %} {% for field in form %} {% render_field field class="form-control" %} {% endfor %} <button type="submit">Create</button> </form> <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script> -
get_form throws TypeError after upgrading Django to 1.10
I recently been upgrading from 1.4 - 1.11 (incrementally), and since going from 1.9 to 1.10 I am having an issue with get_form(). It seems my context doesn't contain "form" and when the super get_context_data is called, it tries to pass an empty get_form() call to fill form. Any clue why this is giving an error now? Internal Server Error: /messages/threads/6/ Traceback (most recent call last): File "C:\Users\LT\Envs\django111\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\LT\Envs\django111\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response response = self._get_response(request) File "C:\Users\LT\Envs\django111\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\LT\Envs\django111\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\LT\Envs\django111\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\LT\Envs\django111\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\LT\111\project\messages\views.py", line 93, in dispatch return super(MemoCreateView, self).dispatch(request, *args, **kwargs) File "C:\Users\LT\Envs\django111\lib\site-packages\django\views\generic\base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "C:\Users\LT\Envs\django111\lib\site-packages\django\views\generic\edit.py", line 213, in get return super(BaseCreateView, self).get(request, *args, **kwargs) File "C:\Users\LT\Envs\django111\lib\site-packages\django\views\generic\edit.py", line 174, in get return self.render_to_response(self.get_context_data()) File "C:\Users\LT\111\project\messages\views.py", line 96, in get_context_data context = super(MemoCreateView, self).get_context_data(**kwargs) File "C:\Users\LT\Envs\django111\lib\site-packages\django\views\generic\edit.py", line 93, in get_context_data kwargs['form'] = self.get_form() TypeError: get_form() takes exactly 2 arguments (1 given) "GET /messages/threads/6/ HTTP/1.1" 500 113089 urls.py from django.conf.urls … -
django rest framework object permission
I don't seem to be triggering the has_object_permission function. class MyPermission(DefaultPermission): def has_permission(self, request, view): return request.user.is_superuser def has_object_permission(self, request, view, obj): import pdb;pdb.set_trace() return request.user == obj.submitter Going to mydomain.com/api/mymodel/100, this should be considered accessing the object, correct? I am viewing object 100 here. Why isn't my trace() being picked up? -
How to run Django legacy projects with gunicorn?
How can I run the legacy of django project 1.5 with gunicorn? $ gunicorn wsgi:application -b 127.0.0.1:8000 [2017-05-18 16:48:00 +0000] [15535] [INFO] Starting gunicorn 19.6.0 [2017-05-18 16:48:00 +0000] [15535] [INFO] Listening at: http://127.0.0.1:8000 (15535) [2017-05-18 16:48:00 +0000] [15535] [INFO] Using worker: sync [2017-05-18 16:48:00 +0000] [15539] [INFO] Booting worker with pid: 15539 [2017-05-18 16:48:00 +0000] [15539] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 557, in spawn_worker worker.init_process() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 136, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 384, in import_app __import__(module) ImportError: No module named wsgi [2017-05-18 16:48:00 +0000] [15539] [INFO] Worker exiting (pid: 15539) [2017-05-18 16:48:00 +0000] [15535] [INFO] Shutting down: Master [2017-05-18 16:48:00 +0000] [15535] [INFO] Reason: Worker failed to boot. This is how I run it on dev mode: $ python manage.py runserver >>> Starting gulp watch >>> gulp watch gulp process on pid 15935 Validating models... 0 errors found May 18, 2017 - 16:53:39 Django version 1.5.12, using settings 'website.settings' Development server is running at http://127.0.0.1:8000/ … -
How to create Django 1.7 app on Webfaction server
I am on Webfaction creating a new server for a new version of my clients site. the app is Django 1.7, and I am trying to create a new Django app of that version, but Webfaction only gives you options for back to 1.8. I thought that I could just create the Django 1.8 app, and than use pip to change it to 1.7.1, and it appears that it worked because if I go into the python library on my production server, and do a 'pip list' it shows me this. However when I try to run Django manage.py functions like 'makemigrations, or migrate' I'm getting an error, and I'm sure it's because It's still trying to run Django 1.8 Is there some step I'm missing into changing the Django app to a lower version ? I am having trouble finding anything in the Webfaction documentation. -
PusherBadRequest Unknown Auth_Key
I'm building this app so that whenever I update an user in the update view, The other view with user's detail displays a change notification. I'm getting PusherBadRequest Unknown Auth_Key, But all the configs are right as you can see in my settings.py. Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'pusherable' ] PUSHER_APP_ID = "340365" PUSHER_KEY = "bbc35fac8ee3918e0048" PUSHER_SECRET = "4ddb65a051f9423982ab" pusher_client = pusher.Pusher( app_id=PUSHER_APP_ID, key=PUSHER_KEY, secret=PUSHER_SECRET, cluster='us2', ssl=True ) Models.py from django.db import models class Users(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) RELATIONSHIP_STATUS = ( ('Single', 'solteiro'), ('Engaged', 'engaged'), ) name = models.CharField(max_length=200) sex = models.CharField(max_length=1, choices=GENDER_CHOICES) Birth_Date = models.DateTimeField('Data de Nascimento') Relationship_Status = models.CharField(max_length=20, choices= RELATIONSHIP_STATUS) def __str__(self): return self.name Views.py from django.shortcuts import render from django.urls import reverse from django.views import generic from.models import Users from .forms import UpdateUser from pusherable.mixins import PusherDetailMixin, PusherUpdateMixin class User(PusherDetailMixin, generic.DetailView): model = Users template_name = "Users.html" class UsersUpdate(PusherUpdateMixin, generic.UpdateView): model = Users form_class = UpdateUsers template_name = "UpdateUsers.html" def get_success_url(self): return reverse('users', kwargs={'pk': self.object.pk}) Templates Users.html {% load pusherable_tags %} {% pusherable_script %} {% pusherable_subscribe 'update' object %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> function pusherable_notify(event, data) { alert(data.user + "has … -
Entry Unique to User
I have a model that keeps track of websites, and want it to be unique to that user. For example if the site is google.com, the user can only enter it once, however still allow multiple users can enter google.com. To give you a better idea here is my models.py: class Site(models.Model): url = models.CharField(max_length=500) tag = models.ForeignKey(Tag) user = models.ForeignKey('customauth.UserProfile') Is there anyway to make the url field unique to users? -
Django Channel group assertion "__asgi_channel__" not in message
Any idea what causes this assertion when I tried to send a message through a django channel group? "assert "asgi_channel" not in message" from channels import Group def ws_connect(message): Group("chatroom").add(message.reply_channel) message.reply_channel.send({"accept": True}) def ws_message(message): Group('chatroom').send({"text": "aloha"}) def ws_disconnect(message): Group("chatroom").discard(message.reply_channel) -
Modify DRF Request objects for dispatch to other views
Context AWS Elastic Beanstalk Worker tiers can be configured to accept a single AWS SQS queue automatically. Incoming messages on this queue can be routed to a single endpoint which some instance in the worker tier will respond to; they show up to the workers as POST events. The software my workers are running is based on Django/DRF. Goal I want my worker tier instances to be able to handle more than one type of incoming event. Ideally, SQS could be configured to deliver the requests to more than one endpoint, but that appears to be impossible. My implementation class DispatchSerializer(serializers.Serializer): "`to` is the name of the destination endpoint; `payload` is the data I want delivered" to = serializers.CharField( max_length=80, ) payload = serializers.JSONField() @api_view(http_method_names=['POST']) @permission_classes([AllowAny]) def dispatch(request): """ Dispatch a request to a sibling endpoint. """ routing_table = { ... # this is specific to my application; # it's just a dict of names to views } serializer = DispatchSerializer(data=request.data) if serializer.is_valid(raise_exception=True): to = serializer.validated_data['to'] try: view = routing_table[to] except KeyError: raise Http404() # https://github.com/encode/django-rest-framework/blob/master/rest_framework/request.py#L183-L187 request._full_data = serializer.validated_data['payload'] return view(request) # If this returns other than 200, SQS simply re-attempts the request later. # No returned data is preserved, … -
How to convert custom id field to normal integer field?
I am desperately trying to get along with Django migrations, please help! This is what I have: class ReceiptNumber(models.Model): id = models.AutoField(primary_key=True, unique=True) This is what I need: class ReceiptNumber(models.Model): number = models.IntegerField() "number" is supposed to have the data that was in id before. While doing this Django creates the default ID field. This one needs to have the same IDs as before in order to not break relations with other tables. Can you please help? I tried a lot of things to tackle this, but I really don't know how to do it. I need a step by step guide. The logical way would be to just clone the id field, but I don't know how and where to do that. Thank you so much for your help! Already wasted a few days on this ._. -
Django: CSS Background image not working after update
I just upgraded my Django 1.10 (Python 3.5) app to Django 1.11 (Python 3.6). Most things still work, but for some reason my CSS background images are not being rendered anymore (I tried with the old version and it still works there). This is only happening for CSS, it still loads normally when it is a HTML tag. This is the first time there I am dealing with an update for my Django app, so I'm not so sure about what is the right way dealing with those minor issues. I've been trying different approaches for the background image, but none of them worked. Here is my failing code, {% extends 'base.html' %} {% load staticfiles %} {% block style %} <style> #top { /*background: url("{% static 'img/skyscraper.jpg' %}") no-repeat center center fixed;*/ background: url("/static/img/skyscraper.jpg"); /*background: url('{{ STATIC_URL }}img/skyscraper.jpg');*/ background-attachment: scroll; background-size: cover; min-height: 700px; } </style> {% endblock %} -
how to get rows which have max value2 when value1 is equal using django queryset
for example rowid value1 value2 1 1 2 2 1 3 3 2 4 then select (1,1,3) and (3,2,4) because row1 and row2 have the same value1, and value2 of row2 is bigger than value2 of row1 thank you! -
Django redirect() - argument to reversed() must be a sequence
urlpatterns = [ url(r'^redirect/', views.redirct) ] def redirct(request): return redirect("http://google.com/") Exception Value: argument to reversed() must be a sequence? -
Django - how to run it on a production server?
I am new to Django Project. I have my app moved to my production server and I have it run: $ python manage.py runserver >>> Starting gulp watch >>> gulp watch gulp process on pid 30427 Validating models... 0 errors found May 18, 2017 - 15:57:08 Django version 1.5.12, using settings 'website.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But it is a production server with an IP, eg: 119.237.27.131 So it **can'**t be running at http://127.0.0.1:8000/ Then what should I do so that the app is running on http://119.237.27.131:8000/ instead? Any ideas? Btw, where is 'website.settings'? -
Django with MongoDB id and _id confusion
Please induldge me: I am new to Django and MongoDB. A tool i am using (called cve-search) populates a mongodb collection 'cves' with documents that have both an _id and id key. In my application i want to generate multiple HTML sections that display values from id which i create in a loop like this: {% for cve in cves %} {% include ".../cveEntry.html" with cve=cve only %} {% endfor %} thus for every cve document something like this is generated: <p> {{ cve.id}} </p> For this my approach was to build a model like: class cves(Document): _id = ObjectIdField() id = StringField() But the cve objects only know an id attribute that contains the original _id value: {'_data': {'_id': None, [... key/values ...], 'id': ObjectId('5911a07bf749d6163d041b0c')}, ...} Am i doing something wrong? Is there a way around it to access the id attribute without renaming the database key? Thank you!