Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - can't update model in database
I have a table in my database (postgresql) that is associated with a model called feedback in my Django app (which is also called feedback). I deleted a couple of columns of the feedback model in the models.py file and then created a migration using: python manage.py makemigrations feedback And then tried to "merge" it with my database using: python manage.py migrate feedback But i got the error: django.db.utils.ProgrammingError: relation "feedback" already exists Of course it exists, but i want to apply the changes i've made. In the migrations folder i have the following files: __init__.py 0001_initial.py 0002_remove_feedback_created_on.py 0003_remove_feedback_is_read.py The last one contains my most recent changes. What should i do? -
Error during WebSocket handshake: Unexpected response code: 200 in Google Chrome
i have a Django chatting app that uses channels, everything is working fine when i try the app using Apple-Safari but when i try Google Chrome i got this error: WebSocket connection to 'ws://gadgetron.store/' failed: Error during WebSocket handshake: Unexpected response code: 200 chat.js: var socket = new WebSocket("ws://" + window.location.host); routing.py: from channels.routing import route from Pchat.consumers import ws_connect, ws_disconnect, ws_receive channel_routing = [ route("websocket.connect", ws_connect), route("websocket.disconnect", ws_disconnect), route("websocket.receive", ws_receive), ] consumers.py: import json from channels.channel import Channel,Group from channels.auth import http_session_user, channel_session_user, channel_session_user_from_http from channels.sessions import channel_session def ws_connect(message): Group('chat_users').add(message.reply_channel) message.reply_channel.send({'accept': True}) @channel_session @channel_session_user def ws_receive(message): msg = message.content['text'] user_id="U" c = chat_room(message=msg,user=user_id) c.save() #message.reply_channel.send({"text": msg ,}) Group('chat_users').send({"text": msg}) def ws_disconnect(message): Group('chat_users').discard(message.reply_channel) -
Entry matching query does not exist in unit test?
I show list of articles (titles of articles) in template. User can sort them by drag and drop. I am trying to write unit test to my sorting view but it raise error (ArticleSortingView). Can someone say whats wrong happens? P.S. I notice that error disappear if I remove delete_old_article_image method which is inside models.py. That method I use to another main thing in my project. When user update article's image this method delete old image and update article with new one. ERROR: Traceback (most recent call last): File "C:\Users\Nurzhan\PycharmProjects\CA\article\tests.py", line 119, in test_article_sorting content_type='image/jpeg' File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35\lib\site-packages\modeltranslation\manager.py", line 381, in create return super(MultilingualQuerySet, self).create(**kwargs) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\query.py", line 399, in create obj.save(force_insert=True, using=self.db) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\base.py", line 796, in save force_update=force_update, update_fields=update_fields) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\base.py", line 820, in save_base update_fields=update_fields) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\dispatch\dispatcher.py", line 191, in send response = receiver(signal=self, sender=sender, **named) File "C:\Users\Nurzhan\PycharmProjects\CA\slider\models.py", line 67, in delete_old_article_image article = Article.objects.get(pk=instance.pk) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\query.py", line 385, in get self.model._meta.object_name article.models.DoesNotExist: Article matching query does not exist. models.py: from django.db.models.signals import pre_save from django.dispatch import receiver class Article(models.Model): head = models.CharField(max_length=200, blank=False) idx = models.IntegerField(default=0, blank=True) … -
MySQLdb module on python 3 and Django 1.11
please help cause I'm confused. I have working site on Django and now i try to migrate on new server. Doing the same steps and install all needed modules, and without apache it's working. But when I starting via apache, getting error : [Sun Sep 17 18:14:25.437300 2017] [:error] [pid 23045] [remote 95.155.91.107:40] 'Did you install mysqlclient or MySQL-python?' % e [Sun Sep 17 18:14:25.437320 2017] [:error] [pid 23045] [remote 95.155.91.107:40] ImproperlyConfigured: Error loading MySQLdb module: dynamic module does not define init function (init_mysql). [Sun Sep 17 18:14:25.437323 2017] [:error] [pid 23045] [remote 95.155.91.107:40] Did you install mysqlclient or MySQL-python? Why? P.S. I have this module : >>> import MySQLdb >>> Please help. My httpd configuration : WSGILazyInitialization On WSGIRestrictEmbedded On WSGIPassAuthorization On WSGIDaemonProcess cardsite python-path=/var/cardsite/:/var/venv_python36/lib/python3.6/site-packages/ WSGIProcessGroup cardsite <VirtualHost *:80> <Directory /var/venv_python36> Require all granted </Directory> CustomLog /var/log/httpd/cardsite-access.log common ErrorLog /var/log/httpd/cardsite-error.log DocumentRoot /var/cardsite/cardsite/ WSGIScriptAlias / /var/cardsite/cardsite/wsgi.py Alias /var/cardsite/cardsite/static /var/cardsite/cardsite/static/ <Directory /var/cardsite/cardsite/static> Require all granted </Directory> <Directory /var/cardsite> <Files wsgi.py> Require all granted </Files> </Directory> RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] </VirtualHost> And my wsgi.py import os import sys PROJECT_DIR = '/var/cardsite' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cardsite.settings") def execfile(filename): globals = dict( __file__ = filename ) exec( open(filename).read(), globals ) activate_this = … -
Django with Plotly, weird urls created
I have a Plotly problem on my Django website. I tried Plotly to visualize some data on my django website but it proved to be too slow and I have now opted for a different solution (highchart). The problem that I can't resolve appeared for the first time after using plotly for a couple of days and is this: In google search console I'm getting many url errors like the followings: 'myfullwebpageurl/lib/codegen' 'myfullwebpageurl/lib/monotone' 'myfullwebpageurl/plots/cartesian/axis_autotype' 'myfullwebpageurl/components/colorscale/color_attributes' 'myfullwebpageurl/style_layer/background_style_layer' and so on.. I am hosting the website with amazon elastic beanstalk and I have pip uninstalled plotly already but this errors remain. Also, I have noticed that they only belong to pages that existed when plotly was installed and not to the newer ones. I can't find a way to debug this as if in search console I click on one of these urls I get a 500 error message, while if I inspect the page where google search console is telling me that the link to that url exists, I can't even find the link to that url. Any ideas? Thanks -
How do I pass a dictionary from one view to another in Django using session?
I have used session to pass dict from one view to another. But it shows this error. I want to create multiple templates submit form. my views.py def view_qr_code(request, *args, **kwargs): # here i wanna retrive session data context = { 'code': 'qrcode' } return render(request, 'add_send_product.html', context) def send_product_add(request): form = SendProductForm(request.POST or None) if request.method == 'POST': if form.is_valid(): instance = form.save(commit=False) data_dict = instance.__dict__ print data_dict request.session['s'] = data_dict return redirect('/qr-code/') else: messages.error(request, "Form is not valid") context = { 'form': form, 'headline': 'Delivery Item' } return render(request, 'add_send_product.html', context) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^send-product/add/$', views.send_product_add, name='add_send_product'), url(r'^qr-code/$', views.view_qr_code, name='qr_code'), ] -
Is it necessary to include sites-enabled directory within nginx.conf
I am following Setting up Django and your web server with uWSGI and nginx tutorial. For two days I was stuck on part Configure nginx for your site. I tried literally everything that I have found searching the internet, mainly I was trying to fix my config mysite_nginx.conf file, but it seems now that it was correct all the time. This is my config file mysite_nginx.conf which of course is symlinked from /usr/local/etc/nginx/sites-enabled/. # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { server 127.0.0.1:8001; } # configuration of the server server { listen 8000; server_name localhost; charset utf-8; client_max_body_size 75M; location /media { alias /Users/username/dev/my_site/mysite/media; } location /static { alias /Users/username/dev/my_site/mysite/static; } location / { uwsgi_pass django; include /Users/username/dev/my_site/mysite/uwsgi_params; } } The Problem I faced Visiting localhost:8000/media/img.jpg or localhost:8000/static/img.jpg always was returning 404 Not Found. In nginx logs all of the requests were mapped to /usr/local/Cellar/nginx/version/html/ which is a symlink to the /usr/local/var/www/ where index.html and 5xx.html files are present. My static/ and media/ were added to the /usr/local/Cellar/nginx/version/html/ so in nginx error logs I saw requests to /usr/local/Cellar/nginx/version/html/static/img.jpg. The Solution that worked for me In nginx.conf file I have included path to the sites-enabled. … -
Should Django forms be populated on client-side when used as popus
My question is best described by example. Consider a table of students. When I click on a student, a pop-up should be opened with comprehensive info on the student. At first, each time the user clicks on a student, I did a GET-request via Ajax, and populated the pop-up with the fetched response. In other words, I did something like this: def my_view(request): if request.method == 'GET': model_instance = MyModel.objects.get(id = request.POST['id']): context = {'my_form': MyForm(instance = model_instance)} msg = render_to_string('my_template.html', context, request = request) return JsonResponse({'object': msg}, safe = False) else: # POST-request for saving input data to db And then in the JS code: $.get(....., function(response){ $(response.object).modal('show'); } The problem with this code is that the pop-up appears with a delay. Well, yes, it's half a second, and yet I would like the response to be instance. What is the best-practice here ? On alternative that occurs to me is the following: when rendering the main page (with student tables), pass an empty form (or as Django doc calls it, unbound form by doing my_form = MyForm()), and then populate it with JavaScript when the user clicks on a student. Well, this approach yields super-fast pop-up rendering, and … -
How to validate a field that is sent several times in django?
I want to create a survey with django and ajax. In survey creation page, user can add several options for each survey. User may add 4 options, or add 10 options or any other number of options. all the options are string and I want to validate them by forms.CharField(). So I created below Form for validating the them. class SurveyOptionForm(forms.Form): option = forms.CharField(max_length=50) How can I validate more than one option by this form? or if there is any better way, what's that? -
Django - DateTimeField in DetailView
How can I display DateTimeField year in urls which is using DetailView ? Here is my code: models.py publish = models.DateTimeField(default=timezone.now) views.py class AktualnosciDetail(DetailView): template_name = 'aktualnosci/detail.html' model = Post urls.py url(r'(?P<slug>[-\w]+)$', AktualnosciDetail.as_view(), name='aktualnosci-detail'), Now my url looks like that: 127.0.0.1/this-is-just-test, but I want my url to look like this 127.0.0.1/2017/09/17/this-is-just-test. How can I do it ? Thanks for help ! -
Django, I deleted AnonymousUser, how to restore
(amazing, I have not found such a question yet!) I deleted part of my users in the db, and accidentally also the AnonymousUser-instance. How do I restore him? (well... him or her, for the sake of political correctness :-P) I do need an instance of him in the db, right? (so far, by quickly browsing my site, I have not run into issues). What would be the problems without him, by the way? But there is no AnonymousUser.objects-manager to create one. And save() is not implemeted anyway, like the docs say. So do I drop the users table and migrate? Will it help and/or can I proceed differently? Thanks a lot :) -
how to run django on nginx
I am going through this tutorial - tutorial And could say everything is okay, when I run the server I see the standard nginx page. But - I did everything and should see my Django page. Nginx refers to standard nginx page instead of my folder in /home/lukp/djangoApp/ Do you have an idea what I should change ? Thanks in advance, -
How to deal with django channels with persisted data on the database
I would like to make a chat application using django and channels. I have two models to achieve a chat like application. Thread - A thread can have list of users. So, it can be used for chat between two users, or groups of user. If it's a group thread, it can have a subject for the group (eg. group name). Message - A message is the actual message sent from one user (sender) to a thread. And any users of thread's user list will have access to it. models: class Thread(models.Model): subject = models.CharField(max_length=255, blank=True) user = models.ManyToManyField(User) class Message(models.Model): thread = models.ForeignKey(Thread) sender = models.ForeignKey(User) sent_datetime = models.DateTimeField(default=timezone.now) body = models.TextField() So, the chat app will have the basic features: Chat with a single user When a user sends a message to a user, django will check if a thread with both sender and receipient exists as the users. If it exist, then create a new message with that existing thread as the foreign key. If it doesn't exits, create a new thread, and create a new message with newly created thread as its foreign key to the thread. Chat with a group of users When a user … -
Django admin list change boolean value on click
models.py class Event(models.Model): name = models.CharField(max_length=80, blank=False) description = models.TextField(blank=True) date = models.DateField(blank=True, null=True) locked = models.BooleanField(default=False) admin.py class EventAdmin(admin.ModelAdmin): list_display = ('name', 'date', 'locked') search_fields = ['name'] ordering = ['date'] admin.site.register(Event, EventAdmin) Is it possible to change "locked" by clicking on the icons in the admin list ? I've tried to add "list_editable = ['locked']", but then the red/green icons aren't visible. Thanks for your help :) -
adding Teammembers issue
In my app users create a project then create a team and invite team members by sending them a mail to sign up to the app. I am trying to figure out how to add the invited user to the team that was created just before. I tried using : TeamMember.user = user but obviously it does not work ;) Could you help me to make it work ? Registration/views.py: def TeamRegister(request): if request.method == 'POST': form = TeamMembersForm(request.POST) if form.is_valid(): user = form.save(commit=False) password = MyUser.objects.make_random_password() user.set_password(password) user.is_active = False user.is_employee = True TeamMember.user = user user.save() current_site = get_current_site(request) message = render_to_string('acc_active_email.html', { 'user':user, 'domain':current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) mail_subject = 'You have been invited to SoftScores.com please sign in to get access to the app' to_email = form.cleaned_data.get('email') email = EmailMessage(mail_subject, message, to=[to_email]) email.send() return HttpResponse('An email have been sent to your user asking him to sign in') else: form = TeamMembersForm() return render(request, 'team_register.html', {'form': form}) app/models.py class Team(models.Model): team_name = models.CharField(max_length=100, default = '') team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) def __str__(self): return self.team_name class TeamMember(models.Model): user = models.ForeignKey(MyUser) team = models.ForeignKey(Team) def __str__(self): return self.user.first_name class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, … -
Matplotlib - Mpld3 fig_to_html() in Django
I am trying to dispaly a scatter of points in mpld3 in my browser. This is my views.py snippet: plt.scatter([1, 10], [5, 9]) fig = plt.figure() html_graph = mpld3.fig_to_html(fig) return render(request, 'home.html', {'graph': [html_graph]}) And inside of home.html: {% for elem in graph %} {{elem|safe}} {% endfor %} But the only thing I see are the controls. I also tried it with: fig, ax = plt.subplot() But this only displays the controls along with the graph, without the scattered points. Any suggestions? Thanks in Advance -
Django Rest Framwork JWT login required
I am using django rest framework jwt authentication. I get token successfully and can add token to cookie. But when i try to reach views that requires login, JWT authentication is not working. Always redirects to login.html. Http request header: Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjozLCJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNTA1NjU3NDgwLCJlbWFpbCI6ImFkbWluQGdtYWlsLmNvbSJ9.Ro507cIEisRle_iKgH4dm3-tSbrrsaCUYtP2CIK9jLM Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjozLCJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNTA1NjU3NDgwLCJlbWFpbCI6ImFkbWluQGdtYWlsLmNvbSJ9.Ro507cIEisRle_iKgH4dm3-tSbrrsaCUYtP2CIK9jLM class SystemUserView(View): @method_decorator(login_required) def get(self, request, user_id): users = list(User.objects.all().values('email', 'id', 'username')) return HttpResponse(HttpResponse(json.dumps(users), content_type="application/json")) urls: from django.conf.urls import url from . import views from .views import SystemUserView, UserAuthenticationView from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token urlpatterns = [ url(r'^$', views.index, name="index"), url(r'^login/?$', UserAuthenticationView.login, name="index"), url(r'^user/(?P<user_id>[0-9]+)/$', SystemUserView.as_view(), name='user'), url(r'^api-token-auth/', obtain_jwt_token), url(r'^api-token-refresh/', refresh_jwt_token), url(r'^api-token-verify/', verify_jwt_token), ] I am newbie to django, so if it is a dump question forgive me. Django version :(1, 11, 5, 'final', 0) Python 3.6.2 -
Django: Changing number of input fields in form based on user input
I'm making a workout diary website with django, where I have the following models in MongoDB: from mongoengine import * class Person(Document): name = StringField(max_length = 200) person_id = IntField(unique = True) def __str__(self): return str(self.person_id) + self.name class Lift(EmbeddedDocument): lift_id = IntField(unique=True) name = StringField(max_length=200) #e.g. bench press, etc sets = ListField(IntField()) # No of reps in each set def __str__(self): return self.name class Cardio(EmbeddedDocument): cardio_id = IntField(unique=True) name = StringField(max_length=200) duration = IntField() #Number of minutes distance = IntField() #Number of metres def __str__(self): return self.name class Workout(Document): id = IntField(unique=True, null=False) date = DateTimeField() person = ReferenceField(Person) lifts = ListField(EmbeddedDocumentField(Lift)) cardio = ListField(EmbeddedDocumentField(Cardio)) def __str__(self): return str(self.date)+" "+self.person.name Since the number of EmbeddedDocumentFields in the lifts and cardio ListFields of Workout can theoretically be infinite, I need to allow the user to specify how many lifts (corresponding to "sets" in the gym) and/or cardio activities they would like to add to their workout. Thus, my form needs to have a dynamic number of inputs based on an initial user input. My question is, does Django cover this is some way, or do I need to use Javascript? -
eventlet.monkey_patch() throws an exception: The SECRET_KEY setting must not be empty
I have a Django project. The packages I use: Django 1.11, Eventlet 0.21.0. Python version is 3.4.3. There are the following configuration files: 1) The main project's configuration file settings.py. It's main role to import one of the other's two configuration files. try: from .settings_local import * except ImportError: from .conf.common import * 2) settings_local.py. The purpose of this file to import all the settings from common.py and override those inside the file's body (or add some new settings) for example for testing purposes: from .conf.common import * ... 3) common.py. The file that contains all the configurations settings. import eventlet eventlet.monkey_patch(all=True, MySQLdb=True) ... When I try to check configuration I get the following error: ./manage.py check Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/vagrant/.virtualenvs/<project_name>/lib/python3.4/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/vagrant/.virtualenvs/<project_name>/lib/python3.4/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/vagrant/.virtualenvs/<project_name>/lib/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/vagrant/.virtualenvs/<project_name>/lib/python3.4/site-packages/django/core/management/base.py", line 322, in execute saved_locale = translation.get_language() File "/home/vagrant/.virtualenvs/<project_name>/lib/python3.4/site-packages/django/utils/translation/__init__.py", line 195, in get_language return _trans.get_language() File "/home/vagrant/.virtualenvs/<project_name>/lib/python3.4/site-packages/django/utils/translation/__init__.py", line 59, in __getattr__ if settings.USE_I18N: File "/home/vagrant/.virtualenvs/<project_name>/lib/python3.4/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/vagrant/.virtualenvs/<project_name>/lib/python3.4/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/vagrant/.virtualenvs/<project_name>/lib/python3.4/site-packages/django/conf/__init__.py", line 110, in __init__ mod = … -
How to create a table with non-unique id and have it as foreign key in another table?
I have the following tables in models.py: class Part(models.Model): partno = models.CharField(max_length=50, unique=True) partdesc = models.CharField(max_length=50, default=None, blank=True, null=True) class Price(models.Model): part = models.ForeignKey(Part, on_delete=models.CASCADE, null=True) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) qty = models.IntegerField(default=1) price = models.DecimalField(max_digits=9, decimal_places=2) currency = models.ForeignKey(Currency, on_delete=models.CASCADE) datestart = models.DateTimeField(auto_now_add=True, blank=False, null=False) class Meta: unique_together = (('supplier', 'part'),) This is properly working. The problem is I have many part numbers which are their replacements. For example part 1001-01, 1001-02, 1001-03 are all the same part. Still, I have all of them in my Part table. I need to match them in another table, so I don't need to enter price for each of them separately. There must be a unique key representing all of these three items. Question: How do I setup a "part number match table" and have a foreign key to this table in my Price table? (Rest is optional to read which are my opinions/problems so far, might help though) 1: I tried to setup the table like this: class PartMatch(models.Model): id = models.IntegerField(primary_key=True, unique=False, null=False, db_index=True) part = models.ForeignKey(Part, unique=False, on_delete=models.CASCADE) But I get an error while migrating: items.PartDetails.partmatch: (fields.E311) 'PartMatch.partmatchid' must set unique=True because it is referenced by a foreign key. … -
Unable to add custom header to response
I am unable to add a custom header to a response that is returned from render(): response = render(request, 'my_template.html', {'ctx1': 1, 'ctx2': 2}) response['My-Custom-Header'] = 'abc12345' return response On Chrome, the response has the template rendered properly, but it does not have the custom header. If I print the response object before returning, I see that it has my custom header. I am using Django 1.11.4 and Python2. -
How to create Django Models based on DTD file
I am new to this xml and dtd files. I need your help on how to create my models in order to upload an xml file in it. The files i have to work with can be found under these 2 links: XML fomat: https://webgate.ec.europa.eu/europeaid/fsd/fsf/public/files/dtdFullSanctionsList/content?token=dG9rZW4tMjAxNw DTD format: https://webgate.ec.europa.eu/europeaid/fsd/fsf/public/files/dtdFullSanctionsListSchema/content?token=dG9rZW4tMjAxNw The DTD file looks like this: <?xml version="1.0" encoding="UTF-8"?> <!ELEMENT WHOLE (ENTITY+)> <!ATTLIST WHOLE Date CDATA #REQUIRED > <!ELEMENT ENTITY (NAME+, ADDRESS*, BIRTH*, PASSPORT*, CITIZEN*)> <!ATTLIST ENTITY Id CDATA #REQUIRED Type (E | P) #REQUIRED legal_basis CDATA #IMPLIED reg_date CDATA #IMPLIED pdf_link CDATA #IMPLIED programme CDATA #IMPLIED remark CDATA #IMPLIED > <!ELEMENT NAME (LASTNAME?, FIRSTNAME?, MIDDLENAME?, WHOLENAME?, GENDER?, TITLE?, FUNCTION?, LANGUAGE?)> <!ATTLIST NAME Id CDATA #REQUIRED Entity_id CDATA #REQUIRED legal_basis CDATA #IMPLIED reg_date CDATA #IMPLIED pdf_link CDATA #IMPLIED programme CDATA #IMPLIED > <!ELEMENT LASTNAME (#PCDATA)> <!ELEMENT FIRSTNAME (#PCDATA)> <!ELEMENT MIDDLENAME (#PCDATA)> <!ELEMENT WHOLENAME (#PCDATA)> <!ELEMENT GENDER (#PCDATA)> <!ELEMENT TITLE (#PCDATA)> <!ELEMENT FUNCTION (#PCDATA)> <!ELEMENT LANGUAGE (#PCDATA)> <!ELEMENT ADDRESS (NUMBER?, STREET?, ZIPCODE?, CITY?, COUNTRY?, OTHER?)> <!ATTLIST ADDRESS Id CDATA #REQUIRED Entity_id CDATA #REQUIRED legal_basis CDATA #IMPLIED reg_date CDATA #IMPLIED pdf_link CDATA #IMPLIED programme CDATA #IMPLIED > <!ELEMENT NUMBER (#PCDATA)> <!ELEMENT STREET (#PCDATA)> <!ELEMENT ZIPCODE (#PCDATA)> <!ELEMENT CITY (#PCDATA)> <!ELEMENT COUNTRY (#PCDATA)> <!ELEMENT OTHER … -
Can't login to django admin with superuser loaded via fixtures
I added superuser via fixtures: python manage.py loaddata data.json Here my data.json: [ { "pk": 1, "model": "auth.user", "fields": { "username": "admin", "first_name": "admin", "last_name": "admin", "is_active": true, "is_superuser": true, "is_staff": true, "groups": [], "user_permissions": [], "password": "admin", "email": "admin@mail.com" } } ] Then I try to login to admin but had error: "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive." The output dumpdata auth.user --indent 4 > output.json show thet [ { "pk": 1, "model": "auth.user", "fields": { "username": "admin", "first_name": "admin", "last_name": "admin", "is_active": true, "is_superuser": true, "is_staff": true, "last_login": "2017-09-17T13:01:51.009Z", "groups": [], "user_permissions": [], "password": "admin", "email": "admin@mail.com", "date_joined": "2017-09-17T13:01:51.009Z" } } ] I use django1.6 and sqlite3 What i'm wrong? -
Django Admin wont allow me to allocate permissions to Users or Groups
I am using django 1.8.6 and have a new application created in a virtualenv using python manage.py startproject. I have set up my INSTALLED APPS and my database settings (postgresql) and I have run migrate to create the backend. So far all seems fine. I then created a superuser using the createsuperuser command and that all seemed to go fine too. My admin.py file is in place and the content of which is as follows: from django.contrib import admin from django.contrib.admin import AdminSite from myapp.models import mymodel Class mymodelAdmin(admin.ModelAdmin): list_display = {col1, col2, col3} admin.site.register(mymodel, mymodelAdmin) All what appears to be fairly simple standard stuff, so far so good. I'm using apache to render my webpages and having configured my virtualhost stuff I can happily log in to my admin page and see everything I have registered plus the default django admin stuff. I can create a new user with no problem and I can create a new Group with no problem. Where I am running into trouble is I ma not able to assign any standard permissions to with my new user or my group. I can see the list of permissions from my database with no problem but … -
token issue while creating and updating an user
In my app I ask a user to invite a teammate by inviting him to the appli. I did it by giving the user that ability to create a user that stay inactive until the teammate sign into the application. The worflow is the following: 1) User create a Teammate user using only the Email 2)a random password is generate 3)the user is saved into the database as inactive 4) An email is sent to the teammate to sign in 5) The teammate update his profile give a First name, last name update his password and is now active on the app. I do not know why it does not update the right user but the user with pk=1 Could you have a look and tell me what is wrong with my code please ? url.py: from django.conf.urls import url, include from registration import views app_name = 'registration' urlpatterns = [ url(r'^hr_register/$', views.registerHR, name='hr_register'), url(r'^auth_HRlogin/$',views.HR_login,name='HRlogin'), url(r'^update/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',views.CandidateSignIn,name='CandidateSignIn'), url(r'^auth_logout/$',views.user_logout,name='logout'), url(r'^auth_team_register/$', views.TeamRegister, name='team_register'), email sent: {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, http://{{ domain }}{% url 'registration:CandidateSignIn' uidb64=uid token=token %} {% endautoescape %} views.py def CandidateSignIn(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user …