Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DRF- OneToOneField How to limit unique User to the type of UserAccount
Problem I am writing an app that has two different type of user accounts (Students and Teachers) that which links my base user (which is a custom user inherited from django.contrib.auth.models.AbstractUser) using a OneToOneField. when working with django rest framework Create view using the CreateModelMixin, I was able to create a Student account using a just created base user, THEN I was able to use the same base user to create a Teacher account. Only one type of user (either teacher or student) should be created using one unique base user However that is not the case, I can now create both a student and a teacher account with just one base user. Background So I have the following data structure below in my django app to describe the structure of my users auth.models.User accounts.models.CustomUserModel (inherited from AbstractUser) student.models.StudentModel (OneToOne to CustomUserModel) teacher.models.TeacherModel (OneToOne to CustomUserModel) with the following to be the model schema for StudentModel, and TeacherModel students.models.StudentModel.py class StudentModel(models.Model): # settings.AUTH_USER_MODEL = accounts.CustomUserModel user = models.OneToOneField( settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) teachers.models.TeacherModel.py class TeacherModel(models.Model): # settings.AUTH_USER_MODEL = accounts.CustomUserModel user = models.OneToOneField( settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) students.api.views.py class StudentUserCreateListSearchView(mixins.CreateModelMixin, generics.ListAPIView): lookup_field = 'id' serializer_class = StudentUserSerializer def perform_create(self, serializer): serializer.save() Question How … -
Handle mutitple forms in django template for loop
I am facing problems handling forms in django template for loop using jquery {% for comment in commets %} <!-- reply to comment --> <form id="replyform" action="" method="POST"> <input type="hidden" name="comment-id" value="{{comment.id}}"> <textarea id="text"> </textarea> </form> {% endfor %} <script> $("#replyform").submit(function(event){ event.preventDefault() var gettext= $("#text",this).val(); }) </script> Since the form is in a for loop, it there for means more than one form is created, depending on the number of comments present. The problem arises when i click the submit button, my jquery submit function is not working , but works only for the first form created in the for loop. How can i go about making all the forms created work with jquery submit. -
Creating a function in the view. "Referenced before assignment"
I'm trying to create a simple function to receive my request data. Well i create: def get_request(field_name): data = request.GET.get('%s'%(field_name), False) return data This raises the following exception: local variable 'brand' referenced before assignment But when i using in my view data = request.GET.get('field_name', False) all works correctly. What is missing in my function to make it work in my views.py file.My view.py using view with look like this: def home(request) get_request(field_name) return render(request, 'home.html') Any help will be appreciated. -
Django return with params
I have reset form and verif form first time reset form is render, and after user submit it will render verif form (at same view). def get(self, request): reset_form = ResetPasswordForm() verification_code = VerificationCode() return self.render_to_response({ 'reset_form': reset_form, 'verification_code': verification_code, 'base_url': settings.BASE_URL, }) def post(self, request): reset_form = ResetPasswordForm(request.POST) verification_code = VerificationCode() if reset_form.is_valid(): messages.success( request, _('Your reset password request has been processed, please check your email.')) verif = False elif verification_code.is_valid(): messages.success( request, _('Code Valid')) verif = True return self.render_to_response({ 'reset_form': reset_form, 'verification_code': verification_code, 'verif': verif, 'base_url': settings.BASE_URL, }) template.html {% if verif %} {% crispy verification_code %} {% else %} {% crispy reset_form %} {% endif %} -
Simple connection of Angular login to Django authentication
I can't seem to find anywhere that simply explains how I can link an Angular login form and take advantage of the Django login/user authentication side of things. I want to make my app require a login before managing any data. The post/delete requests already don't go through if not signed in but you can still access and press the buttons. If this is a repeated thread then I apologise but I couldn't seem to find what I need? I might just be thinking about it the wrong way, any help appreciated! -
How to pass image to requests.post in python?
Sorry Guys, i am new to Django, i am stuck with images upload. what i am doing is, i have a REST_API for image upload. I pass the image and inside API get that image by using request.FILES['fileToUpload']. Now i have an external API, which uploads image on my behalf, that's API is working fine on postman. Here is path of that API. http://164.68.110.65/file_load.php But in Django. i am not able to pass image to this API. i have tried many ways. like these. image = request.FILES['fileToUpload'] temp = Image.open(image) byte_io = BytesIO() temp.save(byte_io, 'png') files = {'fileToUpload': byte_io.getvalue() } response = requests.post( self.URL, files=files) print(response.status_code, response.content, response.reason) but it always giving me error that image format is not matched. can you please tell me, in python requests, how we should pass images or files that are got my request.FILES['file_name_any']. Thanks. I will be very thankful for your favor. -
Django tried these URL patterns error 404
my site used to be ok but since I moved my website from my old server to new one suddenly my inner pages does not appear to work (my main page works ok) and I get 404 error with saying none of url patterns match the link. I think I should change something due to changing the server but I don't know what. this is my primary urls.py: urlpatterns = [ url(r'^',include('BestOfBrands.urls')), url(r'^admin/', admin.site.urls), # url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^accounts/', include('allauth.urls')), url(r'^search/', include('haystack.urls')), ] and this is my urls.py file which is in "BestOfBrands" Folder (my webapp folder): urlpatterns= [ url(r'^$', views.index, name='index'), url(r'^(?P<cg>[-\w]+)-Category/$', views.category, name='category'), url(r'^(?P<cg>[-\w]+)-Category/(?P<scg>[-\w]+)-SubCategory/(?P<s2cg>[-\w]+)-Brands/$', views.sub2category, name='sub2category'), url(r'^(?P<cg>[-\w]+)-Category/(?P<scg>[-\w]+)-SubCategory/(?P<s2cg>[-\w]+)-Brands/(?P<br>[-\w]+)/$', views.brand, name='brand'), url(r'^(?P<sub2category_id>[0-9]+)/vote/$', views.vote, name='vote'), url(r'^(?P<brand_id>[0-9]+)/comment/$', views.comment, name='comment'), url(r'^(?P<comment_id>[0-9]+)/replycomment/$', views.replycomment, name='replycomment'), url(r'^(?P<s2url>[-\w]+)/addbrand/$', views.addbrand, name='addbrand'), url(r'^(?P<usern>[-\w]+)-Profile/$', views.profile, name='profile'), url(r'^Change-Avatar/$', views.changeavatar, name='changeavatar'), url(r'^upload-avatar/$', views.uploadav, name='uploadav'), url(r'^(?P<comment_id>[0-9]+)/like/$', views.like, name='like'), url(r'^(?P<rcomment_id>[0-9]+)/likereply/$', views.likereply, name='likereply'), ] -
How to PATCH Django Test Server with cURL
In my API, I have the following dynamics: POST a processing request to the API. Do some processing in the background. When the processing is done, a computer will PATCH the API's original request status field with cURL. These steps do work when I test them with a normal server, i.e., python manage.py runserver. However, when I try to automate tests within Django, I get: curl: (7) Failed to connect to 127.0.0.1 port 80: Connection refused Port 80 is what is specified under the django.test.client module with 'SERVER_PORT': '80', so I really don't get why that wouldn't work. -
Django form modelmultiplechoicefield
I filtered and listed matches but when I try to select and add matches, the matches I have selected are not added. views.py def creategame(request,tournamentslug): form=GameForm(request.POST or None) tournament = get_object_or_404(Tournament, slug=tournamentslug) form.fields["match"]=forms.ModelMultipleChoiceField(widget=forms.SelectMultiple(attrs={'class':'matchc'}),required=False,queryset=Match.objects.filter(name__icontains=tournament.name)) html <div class="form-item"> <label for="id_match" class="rl-label" style="margin-bottom: 10px;">Match:</label> {{ form.match }} </div> -
ListView unrelated model lookup
I'm looking for a way to bring data from one model into a view of another model for a ListView. Basically, when the user opens up the listview of the vocabulary model, I need to look up and pull out the associated pinyin field from the dictionary model by using the vocab field. There is some example code at the bottom of the codeview that would be how I would match up a Vocabulary.vocab with a Dictionary.pinyin. ############### Models class Vocabulary(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) vocab = models.CharField(max_length=255, blank=False, null=False) translation = models.CharField(max_length=255, blank=False, null=False) level = models.PositiveSmallIntegerField(blank=True, null=True, choices=LEVELS, default=0) audio = models.URLField(blank=True, null=True) objects = RandomManager() class Meta: constraints = [ models.UniqueConstraint(fields=['created_by', 'vocab'], name='User Vocab Duplicate Check') ] verbose_name = "Chinese Vocabulary" verbose_name_plural = verbose_name # this function will be invoked when this model object is foreign key of other model(for example Employee model.). def __str__(self): return self.vocab class Dictionary(models.Model): traditional = models.CharField(max_length=20) simplified = models.CharField(max_length=20) pinyin = models.CharField(max_length=255) simplified_radical = models.CharField(max_length=20) hsk_level = models.PositiveSmallIntegerField(blank=True, null=True, choices=LEVELS, default=0) frequency_rank = models.PositiveIntegerField(blank=True, null=True) phrase_url = models.CharField(max_length=200) radical_url = models.CharField(max_length=200) definition = models.TextField() objects = RandomManager() class Meta: verbose_name = "Dictionary" verbose_name_plural = "Dictionary" … -
Change button depending on if photo is liked in django
I am adding a functionality in my website, where users can like posts. I have successfully done this, however I am having trouble adding one functionality. This is text within a button depending on whether a post is liked or not. Right now the button stays the same no matter if the post is liked or not. models.py class Post(models.Model): file = models.ImageField(upload_to='images/') summary = models.TextField(max_length=600) pub_date = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, through='Like', related_name='likes') def __str__(self): return self.user.username def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') def summary_pretty(self): return self.summary[:50] @property def total_likes(self): return self.likes.count() class Like(models.Model): status = models.BooleanField() post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) views.py def likepost(request, post_id): if request.method == 'POST': post = get_object_or_404(Post, pk=post_id) user = request.user if post.likes.filter(id=user.id).exists(): post.likes.remove(user) return redirect('home') else: like = Like() like.post = post like.user = user like.status = True like.save() post.likes.add(user) return redirect('home') my template: {% if post.likes.status == True %} <a href="javascript:{document.getElementById('likepost{{ post.id }}').submit()}"><button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Unlike {{ post.total_likes }} </button></a> {% else %} <a href="javascript:{document.getElementById('likepost{{ post.id }}').submit()}"><button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Like {{ post.total_likes }} </button></a> {% endif %} -
django assigns incorrect media url
I am (locally) creating a (dockerized) production setup for my django project. I am using django with gunicorn and nginx. Nginx handles static and media files, which work fine, as I can access them by manually entering the correct url. While django does correctly link to static files, the urls to media files are wrong. For media files it skips the port in the url, while for static files it does not. I tried to remove trailing '/', tried to set MEDIA_URL = 'localhost:1337/media/', among other things. I don't understand why the static urls are correct and the media urls are not as I set them up in the exact same way: settings.py: DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = 'path/to/static' MEDIA_URL = '/media/' MEDIA_ROOT = 'path/to/media' example of (correct) django link to static file: 'http://localhost:1337/static/path/to/file example of django link to uploaded media file: 'http://localhost/media/path/to/file' actual location of media file: http://localhost:1337/media/path/to/file -
How to learn Django Rest API and implement
What are the ways I can master in REST API and build some good projects in REST API? -
Inheritance model update to its parent model
I need extend a model from another model. Case: core/models.py class City(Master): zipcode = models.IntegerField() Master is a abstract model. custom/models.py from core.models import City class City(City) newfield = models.CharField(max_length=20) I have tried with proxy model but it is not what I need, since proxy model adds a new table. https://docs.djangoproject.com/en/2.2/topics/db/models/#proxy-models I need is that when I migrate add the new field to City. -
Is it possible to create a custom table view in django-admin?
Is it possible to create a custom page in the admin with a custom queryset which is going to populate a table. The data which is going to be populated in the table is complex, it needs to contain 3 different models with some certain relationship (I already have that but I am exporting it to xls instead.),so far I am thinking about just extending the urls.py (the admin urls) with some custom url + the view, but that would change my consistent look of the admin. What would be the best approach for this? -
how to convert a datetime.date object to string in python
When trying to fetch dates from mysql, and doing a json.dunps on the result for sending it back to html, get this following error : TypeError: datetime.date(2019, 6, 26) is not JSON serializable My db result set looks like : [[(B, datetime.date(2019, 6, 26)), (A, datetime.date(2019, 6, 26))], [(A, datetime.date(2019, 6, 26)), (B, '0000-00-00')]] Tried converting the date object to string using strftime. Does not work. row_headers = [x[0] for x in cur.description] for result in rows: json_data.append(zip(row_headers, result)) for tup in i: core, last_modified = tup if last_modified is not None: last_modified = datetime.strftime(last_modified, '%d-%m-%M') t = datetime.datetime(last_modified) t.strftime('%m-%d-%Y') final_result = {'data': json_data} return HttpResponse(json.dumps(final_result), content_type='application/json') -
Why logging.handlers.RotatingFileHandler prints unknown characters?
I want to store django logs in a file on disk. So I'm using the following dictConfig. But when I check my log file, I see there are some unknown characters printed! What's the problem? LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'django.server': { '()': 'django.utils.log.ServerFormatter', 'format': '[{server_time}] {message}', 'style': '{', } }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, }, 'handlers': { 'django.server': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'django.server', }, 'logfile': { 'level': 'INFO', # 'filters': ['require_debug_false'], 'formatter': 'django.server', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR, 'carpooling.log'), 'maxBytes': 50 * 2**20, # 50MB 'backupCount': 3, }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'filters': ['require_debug_false'], 'include_html': True, }, 'null': { 'class': 'logging.NullHandler', }, }, 'loggers': { 'django': { 'handlers': ['null'], 'propagate': False, }, 'django.server': { 'handlers': ['django.server', 'mail_admins', 'logfile'], 'level': 'INFO', 'propagate': False, }, } } When I request to http://127.0.0.1:8000/ on my browser, I see the [21/Aug/2019 18:28:17] "GET / HTTP/1.1" 200 1868 on console but in the log file the record is as follows: [21/Aug/2019 18:28:17] [m[m[m"GET / HTTP/1.1" 200 1868[0m[0m[0m -
what's the best practice of Spring data JPA query on many optional parameters?
I have a mysql table with many columns, and the users need to query based on arbitrary column (or columns). In django I can easily test the existence of the query parameters and append the queryset likewise. But I'm new to JPA, which seems u have to declare all the possible combinations of query parameters in JpaRepository. or u will have to concatenate the raw sql yourself. So whats the best practice of JPA on arbitrary combination of query parameters? Thank u. -
Install Django with pip but can not see in pip list
I have created virtual environment with python 3.6.Trying to install django with pip.When I run pip install django command, it prompts that requirement already satisfy but I cannot find the django in pip list. $pip install django Requirement already satisfied: Django in /usr/lib64/python2.7/site-packages (1.11.21) Requirement already satisfied: pytz in /usr/lib/python2.7/site-packages (from Django) (2019.1) when I try to check django version on python shell . >>> import django Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'django' Even i have checked in /usr/lib/python2.7/site-packages dir, i cannot find django. How do I fix this? -
Django: Adding a test that has its own set of models
I have a peculiar Django package that defines tools for working with models. This means that I need to write tests in which I define a bunch of model classes, and then do tests on them. Note that for each test, I need to manually write a separate collection of model classes. Is that possible with Django? How can I tell Django "for this test, please use these 7 model classes I defined"? -
Python: Using 'Null' for mysql.connector's port argument
I have a mysql database and I fetch it via a domain like www.mydomain-database.com. this domain is given by a company for accessing my database by phpmyadmin. When I browse this domain, it fetches phpmyadmin login page. I try to connect to this database by the following code: db = mysql.connector.connect( host = "www.mydomain-database.com", user = "root", passwd = "**", database = "database", charset = 'utf8', use_unicode=True ) When I run this, I get the following exept: Can't connect to MySQL server on 'https://www.mydomain-database.com:3306' (-2 Name or service not known) As you can see, connector adds port 3306 to my host; but the url with this port is not valid & it doesn't fetch the phpmyadmin! So, for canceling that change, I added the port = "" as an argument for my connection but I got another error that mentioned the port must be integer! Now the question is, how can I remove that port number when connector tries to connect the host? -
Django query on multiple related objects
I'm having trouble doing a query spanning between a lot of models. This is the query I do to list all animals with encounter.status 'in-progress' and the date immunization date is in the futur. def current_with_futur_vaccines(self): Immunization.objects.filter(recorded__gte=datetime.now())) return ( self.filter( status="in-progress").filter( subject__immunizations__recorded__gte=datetime.now(), ) .select_related("subject") .prefetch_related("subject__immunizations", "location") ) The things is when I want to list the immunizations from the query I get all the immunizations for this animal and not only the immunizations that have to take place in the futur. {% for immunization in object.subject.immunizations.all %} {{ immunization }} {% endfor %} This is the model class Animal(models.Model): name = models.CharField(max_length=250) class Encounter(models.Model): subject = models.ForeignKey(Animal, on_delete=models.PROTECT) status = models.CharField(max_length=11) class Vaccine(models.Model): name = models.CharField(max_length=250) class Immunization(models.Model): subject = models.ForeignKey( Animal, on_delete=models.PROTECT, related_name="immunizations" ) planned_date = models.DateTimeField(default=timezone.now) vaccine = models.ForeignKey(Vaccine, on_delete=models.PROTECT) -
Problem when creating a loop that displays forms
I have an activity table, and the user can select a few of those activities. Based on his selection I redirect him to a new page where he has to select for each activity he previously selected a list of subactivities. So I loop over the activities and I filter the queryset (subactivities) for each of the forms.It is displayed properly but when submitting the form it is invalid. At first I thought it could come from the form sharing the same name but even with one form the error is till there. I have tried to print out what the form looks like after selecting both Aluminium and Plastic upcycling: [21/Aug/2019 15:26:53] "POST /subactivities/ HTTP/1.1" 500 59980 False <tr><th><label for="id_subactivity">Select specific activities:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><select name="subactivity" required id="id_subactivity" multiple> <option value="Aluminium upcycling">Aluminium upcycling</option> <option value="Plastic Upcycling">Plastic Upcycling</option> </select></td></tr> Internal Server Error: /subactivities/ Traceback (most recent call last): File "C:\Users\lavoye\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\lavoye\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view blog.views.Subactivities didn't return an HttpResponse object. It returned None instead. class Subactivities(TemplateView): template_name = 'blog/subactivities.html' context = {'title': 'Subactivities selection page'} def get(self,request): self.context['form_subact_list']=[] for activity in … -
How to add a custom field as metadata when creating a customer with woocommerce api
To begin with, I have a field in my model called afm. I find difficulty in posting among with other fields, the value of this field during the procedure of creating a customer. The procedure of creating an instance of a customer happens from my django application. After creation the instance is also visible (after posting) to the woocommerce --> users section of the administration panel of the website. The custom meta field has the key : wholesale_afm How is it possible to put this custom field in the data dictionary? Below is my unsuccessful attempt. def create_woocommerce_client_individually(wcapi,name,surname,username,email,afm): data = { "first_name": name, "last_name": surname, "username": username, "email": email, "meta":{ "wholesale_afm":"afm", } } wcapi.post("customers", data).json() print("storing the client to woocommerce website...\n") -
Return data from SQL with Django/Python
I am new to python/django and am wondering how I go about doing this. Do i need models.py if I already have the database created? If not, how do i go about querying the db to return the data? I have the settings.py file pointed to the db. settings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'Database', 'USER': 'User', 'PASSWORD': 'Password', 'HOST': 'Server', 'PORT': '1433',