Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DRF - Unable to change user password as user at request is None
my application has an endpoint to change a users password using Django rest framework (DRF). I'm currently running into the following error if I try to change a users password: File "/App/App_API/serializers.py", line 32, in validate_old_password if not user.check_password(value): AttributeError: 'NoneType' object has no attribute 'check_password' [1 urls.py re_path(r'^api/v1/user/change_password$', API_Views.change_password, name='api_change_password'), views.py @api_view(['GET', 'POST']) @authentication_classes([JSONWebTokenAuthentication]) @permission_classes([IsAuthenticated]) def change_password(request): if request.method == 'POST': serializer = ChangePasswordSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() # if using drf auth_token, create a new token if hasattr(user, 'auth_token'): user.auth_token.delete() token, created = Token.objects.get_or_create(user=user) # return new token return Response({'token': token.key}, status=status.HTTP_200_OK) serializers.py class ChangePasswordSerializer(serializers.Serializer): old_password = serializers.CharField(max_length=128, write_only=True, required=True) new_password1 = serializers.CharField(max_length=128, write_only=True, required=True) new_password2 = serializers.CharField(max_length=128, write_only=True, required=True) def validate_old_password(self, value): user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user if not user.check_password(value): raise serializers.ValidationError( _('Your old password was entered incorrectly. Please enter it again.') ) return value def validate(self, data): if data['new_password1'] != data['new_password2']: raise serializers.ValidationError({'new_password2': _("The two password fields didn't match.")}) password_validation.validate_password(data['new_password1'], self.context['request'].user) return data def save(self, **kwargs): password = self.validated_data['new_password1'] user = self.context['request'].user user.set_password(password) user.save() return user To me it seems that the user object within the serialize is simply = None. That again results into the question … -
Django3: Content of child template doesn't load
The posts object is loaded in view post_list using the custom manager defined inside models.py. list.html is trying to display the posts in base.html by iterating over the posts object. But the content of list.html is not rendered inside base.html Relevant screenshot added. base.html {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/blog.css" %}" rel="stylesheet"> </head> <body> <div id="content"> {% block content %} {% endblock %} </div> <div id="sidebar"> <h2>My blog</h2> <p>This is my blog.</p> </div> </body> </html> list.html {% extends "blog/base.html" %} {% block title %}My Blog{% endblock %} {% block content %} <h1>My Blog</h1> {% for post in posts %} <h2> <a href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </h2> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|truncatewords:30|linebreaks }} {% endfor %} {% endblock %} model.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') # Create your models here. class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) … -
how can i resolve ValueError: Field 'cid' expected a number but got ''.?
while performing migration I am getting this error... (env) PS C:\Users\ashwi\Documents\GitHub\AMCH\AMCH_Recruiter> python manage.py migrate Operations to perform: Apply all migrations: Recruiter, admin, auth, contenttypes, sessions Running migrations: Applying Recruiter.0003_auto_20211009_2038...Traceback (most recent call last): File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\models\fields\__init__.py", line 1823, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\ashwi\Documents\GitHub\AMCH\AMCH_Recruiter\manage.py", line 22, in <module> main() File "C:\Users\ashwi\Documents\GitHub\AMCH\AMCH_Recruiter\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\migrations\migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 330, in add_field self._remake_table(model, create_field=field) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 191, in _remake_table self.effective_default(create_field) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\backends\base\schema.py", … -
django foorloop counter restarts in a new page
currently I'm writing a simple todolist with django. I have a view and html file for showing the list of items, and I want a number for each task in the table starting from 1. I'm using {% footloop.counter %} for that in my template. Everything was ok until I wrote the paginator. when you choose to go to the next page, the counter starts from 1 again ,therefor the numbers in the table in each page start from one too. but I want the numbers to be continued in order until the last page. Is there any template tags or code snippets for that? Thanks in advance. here are the codes involved: **list.html:** {% for task in tasks %} <tbody> <tr> <th scope="row" class="col-md-1">{{ forloop.counter }}</th> <td class="col-md-2">{{ task.title }}</td> <td class="col-md-3">{{ task.description|truncatewords:10 }}</td> <td class="col-md-2">{{ task.time|date:"H:i" }} - {{ task.time|date:"D d M , Y" }}</td> </tr> </tbody> {% endfor %} <!--Pagination--> {% if is_paginated %} <div class="container p-4"> <div class="pagination justify-content-center"> <span class="step-links"> {% if page_obj.has_previous %} <a href="{% url 'home:list' 1 %}">&laquo; first</a> <a href="{% url 'home:list' page_obj.previous_page_number %}">previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{page_obj.paginator.num_pages }} </span> {% if page_obj.has_next %} <a … -
Django refreshing records at template only after re-running server
I've just started learning Django and I making my first App. I'm having that weird problem when i adding record to database, it actually adding it there but it won't show them at my page until i reload server by following command python manage.py runserver views.py def createStudent(request): form = StudentForm() if request.method == "POST": form = StudentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("homePage") context = {"form": form} return render(request, "pages/addStudent.html", context) models.py class Students(models.Model): name = models.CharField(max_length=200) surname = models.CharField(max_length=200) card_id = models.IntegerField() unique_id = models.UUIDField( default=uuid.uuid4, unique=True, primary_key=True, editable=False) student_image = models.ImageField(null=True, blank=True, default="default_student.jpg") class Meta: verbose_name_plural = 'Students' #Methods def __str__(self): return f'{self.name} {self.surname}' addStudent.html {% extends "main.html" %} {% block addStudent %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit"/> </form> {% endblock addStudent %} I think that bug appeared after I've started working with static files and added student_image = models.ImageField(null=True, blank=True, default="default_student.jpg") Have anyone faced that problem before? -
Building a Webscraping web-app using Django and Selenium
I am building a webscraping application(or tool) using django and Selenium. I've completed the webscraping part using selenium library in Python. I am wondering how I should convert that into a webapplication, that takes input from user, and scrape accordingly. If you've some links that I can go through I am willing to do that. Any guidance is great help! -
django.db.utils.IntegrityError: UNIQUE constraint failed: new__main_doctor.email
i was trying to change null = False and Unique = True in EmailField and after it started giving me this error: django.db.utils.IntegrityError: UNIQUE constraint failed: new__main_doctor.email I have run the commands makemigrations and migrate but it still giving me this error. I tried undo these and then run commands but it still giving me error. here is my models.py file from django.db import models from phonenumber_field.modelfields import PhoneNumberField import os # Create your models here. import datetime def get_file_path(request, filename): filename_original = filename nowTime = datetime.datetime.now().strftime('%Y%m%d%H:%M:%S') filename = "%s%s" % (nowTime, filename_original) return os.path.join('uploads/', filename) class Doctor(models.Model): name = models.CharField(max_length=20) phone_number = PhoneNumberField(null=False, blank=False, unique=True) email = models.EmailField(null=False, unique=True, max_length=100) city = models.CharField(max_length=100) speciality = models.CharField(max_length=50) doc_image = models.ImageField(upload_to = get_file_path ,null = False, blank = False) kycdocument = models.ImageField(upload_to = get_file_path, null = False, blank = False) class Department(models.Model): dept_name = models.CharField(max_length=20) dept_Email = models.EmailField(max_length=100) dept_password = models.CharField(max_length=200) here is forms.py file from django import forms from .models import Doctor,Department class Doctorslist(forms.ModelForm): class Meta: model = Doctor fields = ('name','phone_number','email', 'city', 'speciality', 'doc_image', 'kycdocument') # widgets = { # 'name': forms.TextInput(attrs = {'class': 'form-control'}), # 'email': forms.EmailInput(attrs={'class': 'form-control'}), # 'city': forms.CharField(attrs={'class': 'form-control'}), # 'speciality': forms.CharField(attrs={'class': 'form-control'}), # } … -
How to pass a file uploaded to another view (next page) for further processing
I am working on a django app where I take an upload of a CSV file however once uploaded I want to simply display columns in another page of that CSV. Is there anyway to do this? something like def index(request): file = request.POST.get('file') redirect('nextpage', file) -
Django Model Struct within a Struct?
I'm trying to create a structure within a structure under Django's models.py. I know how to do this in C but am new to python. For example, I have a class: class OneDay(models.Model) hour1 = ? hour2 = ? ... hour23 = ? hour24 = ? Each hour will have a list of identical properties. I want to apply these properties to every single hour within the OneDay class. I don't believe they are ForeignKeys. class PeriodProperties(models.Model) isX = boolean isY = boolean isZ = boolean R = number P = number So with this I would be able to look up: hour5.isX == false? hour10.R > 50%? Something like that. Can anyone point me in the right direction? Thank you. -
Nginx and uWSGI behind AWS application load balancer with HTTPs
I'm having trouble getting my Django project with an Application Load Balancer ->Nginx -> uWSGI working in AWS. When I do the deployment without the Application Load Balancer everything is working just fine my Nginx is returning at port 443 and no errors but when used with the load balancer the error 504 and 502 happens. At etc/nginx/sites-available/ i have created my django_vps.conf upstream django { server unix:///home/ubuntu/Django_project/mysite.sock; } #redirecting http para https server{ listen 80; server_name servername.com; return 301 https://$host$request_uri; } server { listen 443 ssl http2; server_name servername.com; charset utf-8; #ssl configuration ssl_certificate /etc/ssl/ssl.pem; ssl_certificate_key /etc/ssl/ssl.key; client_max_body_size 75M; #Configurando TLSv1.3 protocol apenas ssl_protocols TLSv1.3; location /media { alias /home/ubuntu/Django_project/media; } location /static { alias /home/ubuntu/Django_project/static; } location / { uwsgi_pass django; include /home/ubuntu/Django_project/uwsgi_params; } } My uWSGI Params ( uwsgi_params ) uwsgi_param QUERY_STRING $query_string; uwsgi_param REQUEST_METHOD $request_method; uwsgi_param CONTENT_TYPE $content_type; uwsgi_param CONTENT_LENGTH $content_length; uwsgi_param REQUEST_URI $request_uri; uwsgi_param PATH_INFO $document_uri; uwsgi_param DOCUMENT_ROOT $document_root; uwsgi_param SERVER_PROTOCOL $server_protocol; uwsgi_param REQUEST_SCHEME $scheme; uwsgi_param HTTPS $https if_not_empty; uwsgi_param REMOTE_ADDR $remote_addr; uwsgi_param REMOTE_PORT $remote_port; uwsgi_param SERVER_PORT $server_port; uwsgi_param SERVER_NAME $server_name; My uwsgi.ini [uwsgi] chdir = /home/ubuntu/Django_project module = Django_project.wsgi home = /home/ubuntu/venv master = true processes = 10 socket = /home/ubuntu/Django_project/mysite.sock vacuum = true … -
Size of file stored on the s3 bucket
I have following model class MediaFile(Media): s3_file = GenericFileField(tag="s3-tag", null=True, blank=True, max_length=300) How can I get size of file stored on s3? I tried this, but it's not work. def file_size(self): try: prefix = get_file_key(self.s3_file) s3 = boto3.resource("s3") bucket = s3.Bucket() return bucket.Object(prefix).content_length except: pass -
Why it show bad request Bad Request: /updateuser/id/
I am trying to update the User details.I have separate MyUser and Profile models join with a Foreign key relation.I have written a nested serializer UsersProfileSerializer.I want to update both MyUser and Profile details together. When I hit submit then in network I see bad request error.May be I am not passing the correct format of response according to my django rest api.When I tried to print request.POST, it show like this in browser console:(if I want to change address then) { address: Array(1), user: {…}} address: ['Not a valid string.'] user: {username: Array(1), bio: Array(1)} [[Prototype]]:Object Please take a look and suggest me my fault.Thanks in advance. My Models are: class MyUser(AbstractUser): bio = models.CharField(max_length=500, blank=True) is_younger = models.BooleanField(default=False) class Profile(models.Model): genders = [ ("M", "Male"), ("F", "Female"), ] user = models.ForeignKey(MyUser, on_delete=models.CASCADE,related_name="profile") age = models.CharField(max_length=2,blank=True,null=True) gender = models.CharField(max_length=1, choices=genders) contact = models.CharField(max_length=12,blank=True, help_text='Contact phonenumber') address = models.CharField(max_length=100, blank=True) The Serializers are: class ListUsersSerializer(serializers.ModelSerializer): class Meta: model = MyUser fields = ['id', 'username', 'email','bio', 'is_younger'] class UsersProfileSerializer(serializers.ModelSerializer): user = ListUsersSerializer() class Meta: model = Profile fields = ['id','age','gender','contact','address','user'] def update(self, instance, validated_data): user_data = validated_data.pop('user') if user_data is not None: instance.user.id = user_data['id'] instance.user.username = user_data['username'] instance.user.email = user_data['email'] … -
How to change initial value of field if clean_{FOO} is invalid?
I have a ModelForm with a clean function for a field. I want to alter the initial value for the field based on some conditional logic in the field: class MyForm(forms.ModelForm): text_field_1 = forms.CharField() def clean_text_field_1(self): data = self.cleaned_data['text_field_1'] if data == 'Hello': self.fields['text_field_1'].initial = 'Goodbye' return ValidationError('Don't say Hello', code='invalid_input') return data However, I can't access the self.fields property of the form from the clean function (it makes no changes). How do I do this? -
How can I fix/ workaround this KeyError when I try to extract from a json via my python API request?
I have been trying to seed a django DB with some covid data from an api and get a KeyError for a particular data type - in the source it is a floating_timstamp ("lab_report_date" : "2014-10-13T00:00:00.000"). (edit: not sure if the type is relevant, but trying to be comprehensive here). I tried doing a more simple API request in python but get the same keyError. Below is my code and the error message. import requests response = requests.get("https://data.cityofchicago.org/resource/naz8-j4nc.json") print(response.json()) The output looks like this: [ { "cases_age_0_17": "1", "cases_age_18_29": "1", "cases_age_30_39": "0", "cases_age_40_49": "1", "cases_age_50_59": "0", "cases_age_60_69": "0", "cases_age_70_79": "1", "cases_age_80_": "0", "cases_age_unknown": "0", "cases_asian_non_latinx": "1", "cases_black_non_latinx": "0", "cases_female": "1", "cases_latinx": "1", "cases_male": "3", "cases_other_non_latinx": "0", "cases_total": "4", "cases_unknown_gender": "0", "cases_unknown_race_eth": "1", "cases_white_non_latinx": "1", "deaths_0_17_yrs": "0", "deaths_18_29_yrs": "0", "deaths_30_39_yrs": "0", "deaths_40_49_yrs": "0", show more (open the raw output data in a text editor) ... "hospitalizations_unknown_gender": "3", "hospitalizations_unknown_race_ethnicity": "16", "hospitalizations_white_non_latinx": "135" } ] So far so good, but if I try to extract the problem key, i get the KeyError: report_date = [] for i in response.json(): ls = i['lab_report_date'] report_date.append(ls) --------------------------------------------------------------------------- KeyError Traceback (most recent call last) /var/folders/h3/5wlbmz0s3jb978hyhtvf9f4h0000gn/T/ipykernel_2163/2095152945.py in <module> 1 report_date = [] 2 for i in response.json(): ----> … -
Django update index after adding records to db programmatically
I added a number of records to a Django db table (machina forums) directly via a script (ie: I did not use the site admin interface). The structure seemed fairly straightforward with no foreign keys in other tables. However the resulting displays are uneven. In a forum index display all of the children forums display under a category. However if I go into the category, only forums added via the admin interface are visible. There does not appear to be any difference in the db records between those that were added programmatically and those added via the admin interface. I am guessing the issue has to do with indexes on the table. However when I use a GUI to view the db all of the indexes show "result set is empty." Any ideas about what is causing the problem and if it is index related, how do I update the index? -
How to implement an external python code to a Django web server?
as from the title, I am trying to implement an external python code to a Django web server. I am quite new to programming so any hints will be surely helpful. Long story short: I am trying to set up a form where the user have to insert an aminoacidic sequence. This sequence should pass to my python script, that is able to compare it with all the sequences already present in the database and gives as a result the most similar ones. My problem is that I am not able to let my form and my script talk each others. I have followed the Django documentation here https://docs.djangoproject.com/en/3.2/topics/forms/ but this did't helped too much. Also roaming online and browse already asked questions here was unfruitful. Please find here below the files: BLAST_page.html (tried both, commented and uncommented) {% extends "base_generic.html" %} {% block content %} <div class="container-fluid" style="text-align: center;" ></div> <form method="post" action= {% url 'BLAST-process' %}> {% csrf_token %} {{ blast }} <label for="sequence">Type or paste your sequence in the box below</label><br><br> <input type="text" id="sequence" class="input_text" name="sequence" value="{{ sequence }}" style="width:600px; height:200px;"><br><br> <input type="submit" value="Submit"> </form> </div> {% endblock %} <!-- <div class="container-fluid" style="text-align: center;" > <form method="POST" … -
How can I pre-process a file's contents being saved into a FileField in Django?
There's a .csv being saved into a FileField in Django 2.2. Before it gets saved, I want to delete some rows in it. This is what I have so far: # A Custom File Field that will modify the file contents before saving it class CustomFileField(models.FileField): # The method that gets called before the save happens def pre_save(self, model_instance, add): file_field = super().pre_save(model_instance, add) file_field = self.update_file_contents(file_field) return file_field def update_file_contents(self, file_field): # NEED TO SOMEHOW UPDATE THE CONTENTS OF # THE file_field HERE BEFORE RETURNING IT return file_field # The model that uses this Custom File Field class MyModel(models.Model): my_csv_file = CustomFileField(upload_to='results/%Y/%m/%d/') I'm not quite sure what my update_file_contents method needs to do to update the contents of the file. Has the file been saved to the filesystem by the time my method is called? Or is it still in memory? Or should I forget making a custom FileField, and simply override my MyModel's save method, so that after the file is saved to the filesystem, I open it again, and modify it like I would any file? -
Trouble trying to get size of Celery queue using redis-cli (for a Django app)
I'm using Django==2.2.24 and celery[redis]==4.4.7. I want to get the length of my celery queues, so that I can use this information for autoscaling purposes in AWS EC2. I found the following piece of documentation: https://docs.celeryproject.org/en/v4.4.7/userguide/monitoring.html#redis Redis If you’re using Redis as the broker, you can monitor the Celery cluster using the redis-cli command to list lengths of queues. Inspecting queues Finding the number of tasks in a queue: $ redis-cli -h HOST -p PORT -n DATABASE_NUMBER llen QUEUE_NAME The default queue is named celery. To get all available queues, invoke: $ redis-cli -h HOST -p PORT -n DATABASE_NUMBER keys \* Note Queue keys only exists when there are tasks in them, so if a key doesn’t exist it simply means there are no messages in that queue. This is because in Redis a list with no elements in it is automatically removed, and hence it won’t show up in the keys command output, and llen for that list returns 0. Also, if you’re using Redis for other purposes, the output of the keys command will include unrelated values stored in the database. The recommended way around this is to use a dedicated DATABASE_NUMBER for Celery, you can also use … -
how can i upload any doc file to my my model from user side and download it,in django?
here I am trying to make a form where users can upload their location and their cv and it should be saved on my Django model. After that, I want to download the same file. for uploading, I am trying this my model looks like this. models.py class canDetails(models.Model): canEmail=models.ForeignKey(candidate,on_delete=models.CASCADE) location=models.CharField("location ",max_length=30) role=models.CharField("role ",max_length=20) cv=models.FileField(upload_to="media/canDetails/",default="") def __str__(self): return self.canEmail in my html <form method="POST" class="form mb-5 mx-1 mx-md-4 mt-4" action="{% url 'canDetails' %}" enctype="multipart/form-data"> {% csrf_token %} <div class="element"> <input type="text" name="location" placeholder="Location" id="location" required /><br> </div> <div class="element"> <input type="text" name="role" placeholder="Role/Stream" id="role" required /><br> </div> <div class="element"> <label for="cv" >Upload your CV</label><br> <input type="file" name="cv" placeholder="CV" id="role" required /><br> </div> <div class="element"> <input type="submit" class="btn btn-success col-md-5" value="Update"> </div> </form> and views.py def canDetails(request): if request.method=='POST': empemail=request.session print(empemail) loc=request.POST['location'] rol=request.POST['role'] print(request.FILES) cv=request.FILES['cv'] canDetails(location=loc,role=rol,cv=cv).save() messages.success(request,"Details updated successfully...!") return render(request,'canDetails.html') return render(request,'canDetails.html') is it the right way I am trying to upload.? I am saving my uploaded file to the media folder here... and here while I am doing it I am getting this error as well canDetails() got an unexpected keyword argument 'location' any suggestion will be greatly appreciated..) -
ModuleNotFoundError: No module named 'myapp.url'
i was creating my django first app. I added this code (urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.url')) ] ) from my project Urls.py file to get my html code from my app url.py, but i keep getting this error when i want to run my server. ModuleNotFoundError: No module named 'myapp.url' -
What exactly the reverse query name in its related model in Django?
I got pretty much the same problem as in Django - reverse query name clash. for the following code: class Supplier(models.Model): unique_id = models.IntegerField(unique=True) name = models.CharField(max_length=255, unique=True) rating = models.FloatField(null=True) last_updated = models.DateTimeField(auto_now=True) default_tariff = models.ForeignKey('Tariff') class Tariff(models.Model): name = models.CharField(max_length=255) supplier = models.ForeignKey(Supplier) end_date = models.DateField(null=True, blank=True) payment_method = models.ManyToManyField(PaymentMethod) region = models.ManyToManyField(Region) My question is: why does the reverse query name for Supplier.default_tariff clashes with the field name Tariff.supplier. I read the docs and I think it should be something like Supplier.default_tariff_set? -
How to get the OAuth code from the redirect URI displayed in the browser using Django URLs
I am integrating Django app with the Docusign API, for the authorization I am using OAuth2 grant_type="code", after passing all the required params to the /oauth/auth (https://account-d.docusign.com/oauth/auth?response_type=code&scope=signature&client_id=33f*******NNNNMNMc-b478-7593294fb3ba&redirect_uri=http://localhost:3000/sales/oauth/callback) endpoint I am getting the Oauth code in the browser to the redirect URI(http://localhost:3000/sales/oauth/callback), I want to fetch this code from my django class view where I have created a path to my view as urlpatterns = [ path( "sales/oauth/callback", OAuthCallbackView.as_view(), name="OAuthCallbackView", ), ] and my view class OAuthCallbackView(APIView): def get(self, request): access_code = request.GET["code"] I want to get the auth code here, since the redirect URI path contains the code (/sales/oauth/callback?code=12312232) I am not able to hit the URL path mentioned above Is there a way I can get the Oauth code in Django -
IntegrityError at /update_dept/1/ NOT NULL constraint failed: main_department.dept_name
I am creating a simple django models of doctors and department. there is not link between them and when I try to update the department then it is show me this error IntegrityError at /update_dept/1/ NOT NULL constraint failed: main_department.dept_name this error is new for me. I check other similar question also but didn't get much. so pls help me. here is my view.py file from django.shortcuts import render from .forms import Doctorslist,Departmentform from .models import Department, Doctor from django.shortcuts import redirect from django.views.generic import (CreateView, DetailView, UpdateView, ListView, TemplateView, DeleteView) from django.contrib.messages import constants as messages import os # Create your views here. def add_show(request): form = Doctorslist() if request.method == "POST": form = Doctorslist(request.POST, request.FILES) form.save() return redirect('/') else: form = Doctorslist() stud = Doctor.objects.all context = {'form':form, 'stu':stud } return render(request, 'main/index.html', context) def update_data(request, id): prod = Doctor.objects.get(id=id) if request.method == "POST": prod.doc_image = request.FILES['doc_image'] prod.kycdocument = request.FILES['kycdocument'] prod.name = request.POST.get('name') prod.phone_number = request.POST.get('phone_number') prod.email = request.POST.get('email') prod.city = request.POST.get('city') prod.speciality = request.POST.get('email') prod.save() messages.success(request, "Product Updated Successfully") return redirect('/') context = {'prod':prod} return render(request, 'main/update_doc.html', context) def delete_data(request,id): if request.method =='POST': pi = Doctor.objects.get(pk = id) pi.delete() return redirect('/') def add_show_dept(request): form = Departmentform() if … -
RabbitMQ mkdir: /var/db/rabbitmq/mnesia: Permission denied
I have uploaded my Django project to the server. Everything works except using Celery. The server uses FreeBSD. Erlang is uploaded, but I have a problem with RabbitMQ. I downloaded rabbitmq-server-generic-unix-3.9.7.tar.xz and then unpacked it in cd /usr/home/my_login/RabbitMQ/. When I try to start the server with cd /usr/home/my_login/RabbitMQ/rabbitmq_server-3.9.7/sbin/rabbitmq-server I am getting a message about the lack of access to create a DB in the path as below mkdir: /var/db/rabbitmq/mnesia: Permission denied Failed to create directory: /var/db/rabbitmq/mnesia So I tried somehow to manually set this path to be different in cd /usr/home/my_login/RabbitMQ/rabbitmq_server-3.9.7/etc/rabbitmq/rabbitmq.conf. In the file I added: RABBITMQ_MNESIA_DIR=/usr/home/my_login/RabbitMQ/rabbitmq_server-3.9.7/db/ But that didn't help either, and I still don't know how to deal with it. I can't access root or sudo commands there -
how to upload django files as background? Or how to increased file upload?
I need to increased file upload speed in Django. Any ways to do this? I guess about to upload files as a background, when user send POST request i just redirect them to some page and start uploading files. Any ways to do this? Or do you know any ways to increased upload speed? Thank you in advance