Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django URL Conflict Despite Specific Views
I'm having an issue when someone goes to do a search in my search box (which corresponds to the 'search' view). The word 'search' is getting picked up by the 'search_category' view and trying to run the query using the word 'search' to match instead. I think i can see why it is happening--essentially the search and search_category views are both looking for a word after my url. I'm just confused as to why the actual views are not getting picked up and the URL's are being mixed up? Here are my views as well: My urlpatterns urlpatterns = [ url(r'^(?P<letter>[a-zA-Z])/$', views.mineral_letter, name='letter'), url(r'^(?P<category>[a-zA-Z\s]+)/$', views.search_category, name='category'), url(r'^$', views.mineral_list, name='list'), url(r'^(?P<pk>\d+)/$', views.mineral_detail, name='detail'), url(r'^search/$', views.search, name='search'), ] my views: def mineral_list(request): minerals = Mineral.objects.all() return render(request, 'minerals/mineral_list.html', {'minerals': minerals}) def mineral_detail(request, pk): mineral = Mineral.objects.get(pk=pk) return render(request, 'minerals/mineral_detail.html', {'mineral': mineral}) def mineral_letter(request, letter): minerals = Mineral.objects.filter(name__istartswith=letter.lower()) return render(request, 'minerals/mineral_list.html', {'minerals': minerals, 'active_letter':letter}) def search(request): term = request.GET.get("q") minerals = Mineral.objects.filter(name__icontains=term) return render(request, 'minerals/mineral_list.html', {'minerals': minerals}) def search_category(request,category): minerals = Mineral.objects.filter(category__icontains=category) return render(request,'minerals/mineral_list.html', {'minerals':minerals}) -
Python import from beyond top-level package
I am developing a Django project for which I wrote some non-web related libraries. My directory structure looks something like this: Main folder Theorem prover here are the things I want to import web app here's where I want to import things from The place where I'm running the app is the web/ folder. What would be the proper way of doing this? -
Django Model Relationships (how to change a relationship)
I am a Django newbie. I have a model list like below. In this example, I have friendlists and friendrequestlists having users, but I want to have users having friendslists and friendrequestlists. How should I modify this code: from django.db import models from datetime import datetime from django.contrib.auth.models import User, Group class Word(models.Model): definition = models.CharField(max_length=350) #add_date = models.DateTimeField(default=str(datetime.now()), editable=False) turkish = models.CharField(max_length=50) english = models.CharField(max_length=50) users = models.ManyToManyField(User) groups = models.ManyToManyField(Group) creator = models.CharField(max_length=50) visibility = models.CharField(max_length=2, default='2') #0(only me), 1(friends), 2(groups), 3(everbody) def __str__(self): return self.english #def add_date_pretty(self): # return self.add_date def summary(self): return self.definition[:50] + "..." class GroupEx(models.Model): group = models.OneToOneField(Group) admins = models.ManyToManyField(User) def __str__(self): return self.group.name class GroupReqList(models.Model): group = models.OneToOneField(Group) member_request = models.ManyToManyField(User) def __str__(self): return self.group.name class UserEx(models.Model): user = models.OneToOneField(User) casel = models.CharField(max_length=12) def __str__(self): return self.user.username class FriendList(models.Model): user = models.OneToOneField(UserEx) friends = models.ManyToManyField(User) def __str__(self): return self.user.user.username class FriendReqList(models.Model): user = models.OneToOneField(UserEx) friend_requests = models.ManyToManyField(User) def __str__(self): return self.user.user.username -
Can't create a custom auth model with "if user.is_authenicated" in html
Hi I am trying to make a register link in my html-file. But it only works when I am already logged in. settings.py AUTH_USER_MODEL = 'users.User' models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.urls import reverse_lazy class User(AbstractUser): # Address plz = models.CharField(max_length=5) ort = models.CharField(max_length=30) strasse = models.CharField(max_length=30) strnr = models.CharField(max_length=5) # Kontakt mobil = models.CharField(max_length=20) forms.py I customized the original UserCreationForm to implement to additional fields: class UserCreate(forms.ModelForm): --snip-- class Meta: model = User fields = ('username', 'password1', 'password2', 'first_name', 'last_name', 'email', 'mobil', 'plz', 'ort', 'strasse', 'strnr',) views.py class UserCreate(CreateView): model = User form_class = UserCreate template_url_suffix = '_create_form' def get_context_data(self, **kwargs): context = super(UserCreate, self).get_context_data(**kwargs) context['head'] = 'Account erstellen' return context urls.py url(r'^user/create/$', views.UserCreate.as_view(), name='user-create'), If I am logged in, I can use the link to create a user instance: <a href="{% url 'users:user-create' %}">register</a> How can I make it work, if one is not logged in??? {% if user.is_authenticated %} <a href="{% url 'users:user-create' %}">register</a> {% endif %} Error: Reverse for 'user-detail' with arguments '(None,)' not found. 1 pattern(s) tried: ['user/(?P[0-9]+)/detail/$'] -
Django deployment with Apache(mod_wsgi) Xsendfile configuration
Can not seem to get xsendfile working with my django application. It is supposed to do the filtering on the django side but I can still access all the files from the media folder. I tried leaving out the media directory but than I get a forbidden page. I'm working on Windows 10 with Apache 2.4, mod_wsgi module and xsendfile module. settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py: urlpatterns += url(r'^media\/(?P<path>.*)$', app.views.download, { 'document_root': settings.MEDIA_ROOT, }), views.py @login_required(login_url='/login/') def download(request, path, document_root): spl = path.split('/') if request.user.is_superuser: response = HttpResponse() response['Content-Type'] = '' response['X-Sendfile'] = os.path.join(settings.MEDIA_ROOT, path) return response else: if (int(spl[1]) == request.user.id): response = HttpResponse() response['Content-Type'] = '' response['X-Sendfile'] = os.path.join(settings.MEDIA_ROOT, path) return response else: return HttpResponse('<h1>This file does not belong to you</h1>') httpd-vhosts.conf: WSGIPythonPath "/Users/admin/_GIT/app-prototype/prototype" <VirtualHost *:80> ServerName localhost:80 ServerAdmin freezer@app.com DocumentRoot "/Users/admin/_GIT/" XSendFile On XSendFilePath "/Users/admin/_GIT/app-prototype/prototype/media/" Alias /static/ "/Users/admin/_GIT/app-prototype/prototype/static/" Alias /media/ "/Users/admin/_GIT/app-prototype/prototype/media/" <Directory "/Users/admin/_GIT/app-prototype/prototype/static/"> Require all granted </Directory> <Directory "/Users/admin/_GIT/app-prototype/prototype/media/"> Require all granted </Directory> WSGIScriptAlias / "/Users/admin/_GIT/app-prototype/prototype/appname/wsgi.py" <Directory "/Users/admin/_GIT/app-prototype/prototype/appname/"> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> -
how setup lookup_field?
AssertionError: Expected view blabla to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly. # If you want to use object lookups other than pk, set 'lookup_field' well I don't want use URL to set pk , I want use pk from query_params for example something like : request.query_params.get('id', None) so how setup lookup_field ? class blabla(mixins.UpdateModelMixin,generics.GenericAPIView): lookup_field = request.query_params.get('id', None) -
Media files not being returned properly
models.py: class FWVersion(models.Model): bin_file = models.FileField(upload_to='fW_media/bin/') date_created = models.DateTimeField(default=timezone.now) name = models.CharField(max_length=64) I am using django-rest-framework to create APIs for uploading and retreiving the latest version of the .bin file. The APIs are working and I am able to upload a .bin file on the server. But when downloading the file again, the server returns the first uploaded file(the oldest one)even though the name, url are of the latest uploaded file. Sometimes rarely however, it returns the latest file. I have checked the server files, they are being uploaded properly. Is this because of some caching by Django or am I missing something? Please help. -
bulk_create in django to insert multiple rows into 2 different tables
I have 2 tables Transaction and TransactionAmount. I get this data in the json format. It would contain both Transaction and TransactionAmount data. I am trying to insert using bulk_create method. Below is my tables : class Transaction(models.Model): transaction_id = models.AutoField(primary_key=True) route_id = models.ForeignKey(PosFlightSchedule, null=False, blank=False) sequence_number = models.ForeignKey(LegDetail, null=False, blank=False) device_id = models.ForeignKey(DeviceInfo) crew_code = models.ForeignKey(Crew) time_of_transaction = models.TimeField() total_quantity = models.IntegerField() manually_added_flag = models.BooleanField(default=False) seat_number = models.CharField(max_length=200, null=True, blank=True) transaction_type = models.CharField(max_length=200) reason_code_id = models.ForeignKey(ReasonCode, null=True, blank=True) total_amount = models.FloatField() amount_by_card = models.FloatField(null=True, blank=True) def __unicode__(self): return u'%s' % self.transaction_id class Meta: verbose_name_plural = "Transaction" class TransactionAmount(models.Model): transaction_id = models.ForeignKey(Transaction) amount_by_cash = models.FloatField() amount_returned = models.FloatField(null=True, blank=True) currency_code = models.ForeignKey(Currency) instances = [ Transaction( route_id=PosFlightSchedule.objects.get(pos_route_id=transaction[i]['route_id']), sequence_number=LegDetail.objects.get(sequence_number=transaction[i]['sequence_number']), device_id=DeviceInfo.objects.get(device_unique_id=transaction[i]['device_id']), crew_code=Crew.objects.get(crew_code=transaction[i]['crew_code']), time_of_transaction=transaction[i]['time_of_transaction'], total_quantity=transaction[i]['total_quantity'], manually_added_flag=transaction[i]['manually_added_flag'], seat_number=transaction[i]['seat_number'], transaction_type=transaction[i]['transaction_type'], reason_code_id=getReasonCode(transaction[i]['reason_code_id']), total_amount=transaction[i]['total_amount'], amount_by_card=transaction[i]['amount_by_card'], ) for i in xrange(0, len(transaction)) ] Transaction.objects.bulk_create(instances) transaction value would be like this : [{ "route_id": "2", "sequence_number": 1, "device_id": 1, "crew_code": "crew1", "time_of_transaction": "05:19:45", "total_quantity": 10, "manually_added_flag": false, "seat_number": "1", "transaction_type": "sale", "reason_code_id": "", "total_amount": 10, "amount_by_card": 100, "cash_details": [{ "amount_by_cash": 100, "amount_returned": 10, "currency_code": "Rupee" }]}] This code works for Transaction table, I am unable to add data (cash_details) to TransactionAmount. How can I include that ? -
Generate models for Oracle DB views using inspectdb
I've been messing around with Django (1.11.1) at home for some time now, and I feel like it's one of the best out there in terms of ease of use. While I easily generated the models for all the tables I had in my Oracle DB using: python manage.py inspectdb > models.py I couldn't find a way to also generate models for my views. I've looked into introspection.py and it seems like it's getting views by default. I just can't figure out how could I make use of them. -
Django is not sending mail
We have a Django application that runs on CentOS. We've created a new feature for password reset using the Django auth and forms. This works when working on development servers but when I deploy this to our production environment the mail with the unique link is not being sent. I've pinpointed the problem to the fact that Django using smtplib is trying to send the e-mail through port 25 with Postfix instead using the settings.py which is pointed to Google server. When i turn Postfix off I get connection refused when trying to reset the password. My settings.py: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'my-mail@gmail.com' EMAIL_HOST_PASSWORD = 'my-pass' DEFAULT_FROM_EMAIL = 'my-mail@gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' SERVER_EMAIL = 'my-mail@gmail.com' Your help is much appreciated, Omer. -
Select a valid choice. ['FRI'] is not one of the available choices
I want a multiple select field in my django form. It does not save the values in database. models.py DAY_OF_WEEK=( ('*', 'All'), ('MON', 'Monday'), ('TUE', 'Tuesday'), ('WED', 'Wednesday'), ('THU', 'Thursday'), ('FRI', 'Friday'), ('SAT', 'Saturday'), ('SUN', 'Sunday'), ) game_day = models.CharField(max_length = 200, choices = DAYS) forms.py game_day = forms.MultipleChoiceField(choices=DAY_OF_WEEK, required=True, label='Game Day') When I click on submit it gives the error: Select a valid choice. ['FRI'] is not one of the available choices. -
Possibility of CSRF-related issues in cached sign up form (Django)
I have a sign up page in a Django project which I've cached (using @cache_page(600) on the view). On the page itself, I'm testing a simple form like so: <form method="POST" action="{% url 'sign_up' %}"> {% csrf_token %} Nickname:{{ form.username }}<br> Password:{{ form.password1 }}<br> Password (repeat):{{ form.password2 }}<br> <input class="btn bcg bs mlt mbs" type="submit" value="OK"> </form> 1) Would caching such a page cache the CSRF token as well? 2)And if it does, would that have a deleterious effect on user sign up in any way? 3) Moreover, what about security vulnerabilities? -
Django - How to deserialize json into a nested object
I have the following problem. I need to create a complex object using data POSTed in json. In the models.py file, I have the main object called "Company": class Company(models.Model): name = models.CharField(max_length=255) descr = models.CharField(max_length=255) def __str__(self): return self.name Then I have "Building": class Building(models.Model): name = models.CharField(max_length=255) city = models.CharField(max_length=255) location = models.TextField() company= models.ForeignKey("Company", related_name="buildings", on_delete=models.CASCADE) And so on with other few classes (i.e. "Floor", "Area", "Room"). The json I get from the POST request is: { "id": 1, "buildings": [{ "id": 3, "piani": [{ "id": 1, "floor": -1, "descr": "underground", "building": 3 }], "areas": [{ "id": 1, "rooms": [{ "id": 1, "floor": 1, "area": 1, "descr": "First Room" }], "descr": "Dev area", "building": { "id": 3, "name": "Sede", "city": "Rome", "location": "mylocation", "company": { "id": 1, "name": "Test", "descr": "Test" } } }], "name": "Sede", "city": "Rome", "location": "mylocation", "company": 1 }], "name": "Test", "descr": "Test" } When I try to create a "Company" object from the json I get, it only creates the following: { "id": 1, "buildings": [], "name": "Test", "descr": "Test" } and not the full structure. My serializers are the following: class EdificioSerializer(serializers.ModelSerializer): piani = PianoSerializer(read_only=True, many=True,) aree = AreaSerializer(read_only=True, many=True) class … -
Lock table in Postgres to allow reading by other transactions, but disallow writing
I'm developing a Django application. There's a functionality where I want to change the database state by reading from, making calculations, and inserting to many tables. This is an atomic procedure, and it can't be only "single-threaded", because the resulting state depends on the order, in which such procedures are executed. For that I use Celery with a single worker. I thought about SERIALIZED isolation level in Postgres, until I had read: Serializable transactions is guaranteed to produce the same effect as running them one at a time in some order But I don't need some, I need the exact order, that's why I chose the message queue. During the procedure I want to disallow writing to the tables I operate on completely, but still allow reading. What least restrictive LOCK mode suits my case? -
Creation of multiple choice field checkbox
Hello i am new with django. I need to create multiple choice field checkbox. I only found this reference but i don't understand how to use it. The reference is : https://books.google.com.lb/books?id=6TDYBAAAQBAJ&pg=PT417&lpg=PT417&dq=check+box+related+to+previous+checkboxes+django&source=bl&ots=TpBaexfc-v&sig=l8N1kjqGtZf2D39gccvoFmGK4TA&hl=ar&sa=X&ved=0ahUKEwjv_b-f8pTUAhWGcBoKHf54DqU4ChDoAQg3MAM#v=onepage&q=check%20box%20related%20to%20previous%20checkboxes%20django&f=false I dont understand how to use it -
Django downloading file:UnicodeDecodeError
I use Django 1.11 to download file.This is my function. def file_downloading(request, filename): path = settings.MEDIA_ROOT+'/' the_file_name = path+filename f_name = filename.split('/')[len(filename.split('/'))-1] wrapper = FileWrapper(open(the_file_name, "r")) content_type = mimetypes.guess_type(the_file_name)[0] response = HttpResponse(wrapper, content_type=content_type) response['Content-Length'] = os.path.getsize(path) response['Content-Disposition'] = 'attachment; filename=%s f_name return response But I got a UnicodeDecodeError when I was trying to download .pdf file.Actually it only works when the file is .txt . When I change the wrapper to open("file_name","rb"),the file can be downloaded, but it can't be opened.How can I deal with this problem? -
needed django users and subusers with limited permissions
I am a beginner of django. I am trying to create a user below the admin say user 1 and below user1 there will be some other users say user2,user3,user4,..user50. So now what i need is admin can access everything, but user should access only some permission say permission 1 and permission 2 and user 2 should access only permission 2 and user should not access another users say user51, user52,etc.. can any one help me Thank q in advance -
Change celery broker with scheduled tasks
I'm changing my Celery backend from redis to rabbitmq. I can get the new broker working with changing my BROKER_URL. However I'm wondering how to migrate existing scheduled tasks from redis to rabbitmq broker? I would like to do this by Python script if possible. -
Run LiveServerTestCase from Docker Selenium with Django 1.11
Since Django 1.11, the option --liveserver was removed from the manage.py test command. I was using this option to allow the liveserver to be reach from the ip address of the machine rather than the localhost with the following command: ./manage.py test --liveserver=0.0.0.0:8000 Unfortunately, this option is gone and I'm looking for a new solution to allow my Docker Selenium image to access my LiveServerTestCase during the tests. -
How to update multiple objects of the same model using ModelForm?
I have multiple Product objects in my project. I want to create a form which updates all Product objects at once. Since Product has many attributes I want to spare some time and do it using ModelForm but I can't figure out how to do that. So there is no particular object I want to update, instead there is many of these objects but I want to set the same attributes for all but not change id (and one other field - OneToOne). I think this might be a solution but can't finish save method. class UpdateMultipleProductObjects(forms.ModelForm): class Meta: model = Product fields = '__all__' def save(self, *args, **kwargs): temporary_object = super(UpdateMultipleProductObjects,self).save(commit=False,*args,*kwargs) Product.objects.all().update(# use temporary object) Do you have any ideas? -
Django sending and receiving a friend request.
I've been struggaling for a while now to fully implement my friends list into django. I've got it so that user send friend requests, they can remove their pending friend request and they can remove someone as their friend, however im struggling to to allow someone to accept a friend request. Here is my code: really sorry for all the code models.py in my likes app class UserLikeManager(models.Manager): def get_all_mutual_likes(self, user, number): try: qs = user.liker.liked_users.all().order_by("?") except: return [] mutual_users = [][:number] for other_user in qs: try: if other_user.liker.get_mutual_like(user): mutual_users.append(other_user) except: pass return mutual_users class UserLike(models.Model): user = models.OneToOneField(User, related_name='liker') liked_users = models.ManyToManyField(User, related_name='liked_users', blank=True) objects = UserLikeManager() def __unicode__(self): return self.user.username def get_mutual_like(self, user_b): i_like = False you_like = False if user_b in self.liked_users.all(): i_like = True liked_user, created = UserLike.objects.get_or_create(user=user_b) if self.user in liked_user.liked_users.all(): you_like = True if you_like and i_like: return True else: return False My views.py in my likes app def like_user(request, id): pending_like = get_object_or_404(User, id=id) user_like, created = UserLike.objects.get_or_create(user=request.user) if pending_like in user_like.liked_users.all(): user_like.liked_users.remove(pending_like) else: user_like.liked_users.add(pending_like) notify.send( request.user, #action=request.user.profile, target=request.user.profile, recipient=pending_like, verb='sent you a friend request view') return redirect("profile", username=pending_like.username) my views.py in my profiles app @login_required def profile_view(request, username): user = get_object_or_404(User, username=username) … -
How to handle array in array in POST? [duplicate]
This question already has an answer here: Sending a form array to Flask 1 answer The Form Data that is sent in the POST is: questions_answers[0][id]:188 questions_answers[0][answers][]:677 questions_answers[1][id]:189 questions_answers[1][answers][]:1684 questions_answers[1][answers][]:1685 questions_answers[2][id]:190 questions_answers[2][answers][]:682 questions_answers[3][id]:191 questions_answers[3][answers][]:683 questions_answers[3][answers][]:685 In other words: questions_answers is an array of objects each object has 2 properties: its id an array of integer Here's what I get in my POST. I'm dumping using a simple print(request.POST): <QueryDict: {'questions_answers[0][id]': ['188'], 'questions_answers[0][answers][]': ['677'], 'questions_answers[1][id]': ['189'], 'questions_answers[1][answers][]': ['1684', '1685'], 'questions_answers[2][id]': ['190'], 'questions_answers[2][answers][]': ['682'], 'questions_answers[3][id]': ['191'], 'questions_answers[3][answers][]': ['683', '685']}> If I try to do this: questions = request.POST.getlist('questions_answers') print(questions) for a in questions: print(a) I get only [] for questions. What am I doing wrong? -
Installing mysqlclient for mariadb on mac os for python3
I have an issue precessing pip install mysqlclient for python3 on Sierra running build_ext building '_mysql' extension creating build/temp.macosx-10.12-x86_64-3.6 clang -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/usr/local/Cellar/openssl/1.0.2k/include -Dversion_info=(1,3,10,'final',0) -D__version__=1.3.10 -I/usr/local/Cellar/mariadb/10.2.6/include/mysql -I/usr/local/Cellar/mariadb/10.2.6/include/mysql/.. -I/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/include/python3.6m -c _mysql.c -o build/temp.macosx-10.12-x86_64-3.6/_mysql.o _mysql.c:1911:42: error: no member named 'reconnect' in 'struct st_mysql' if ( reconnect != -1 ) self->connection.reconnect = reconnect; ~~~~~~~~~~~~~~~~ ^ 1 error generated. error: command 'clang' failed with exit status 1 I have installed MariaDB and xcode-select --install also precessed. -
In django 1.11, /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/registration/login.html (Source does not exist)
I have tried to implement authentication functionality with django1.11. This is urlconf. urlpatterns = [ url(r'', include('django.contrib.auth.urls')), ] As you know, When I go to localhost:8000/login, registration/login.html must be rendered on the browser. but exception has occurred like as follows. TemplateDoesNotExist at /login/ django.template.loaders.app_directories.Loader: /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/registration/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python2.7/dist-packages/django/contrib/auth/templates/registration/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/yuiry/python/myproject_env/example/app/templates/registration/login.html (Source does not exist) I guess, the exception might occur because of the file structure. Namely templates/registration/login.html. I wanna know how can I handle it. I have attached login.html image. Please help me. -
Extend Django User Model to have a selfdefined encrypted password field?
I want to use the password of users to perform some paramiko connections. but Django is storing it in encrypted + hashed format. The Method used for login is based on LDAP (django-python3-ldap) so im thinking to extend user model and store the password in encrypted format and when needed decrypt and use it. can someone help me with this . Thanks Alot