Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
POST request to localhost using Python requests
I have my Django website running on my local server at port 8000. From a separate python file, I want to send a post request triggering one endpoint of my website. But unable to do that even after adding all the required info. Please help!! import requests URL = 'http://127.0.0.1:8000/api/org/create/' client = requests.Session() client.get(URL) csrftoken = client.cookies['csrftoken'] data = dict(csrfmiddlewaretoken=csrftoken) headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'} response = client.post(URL, data=data,cookies=client.cookies, headers=headers) print(response.status_code) It is giving me this error. EC:\Program Files\Python37\lib\unittest\case.py:643: ResourceWarning: unclosed <socket.socket fd=420, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 10510), raddr=('127.0.0 .1', 8000)> outcome.errors.clear() ====================================================================== ERROR: test_org_create (test_org.TestOrg) ---------------------------------------------------------------------- Traceback (most recent call last): File "\test_org.py", line 13, in test_org_create csrftoken = client.cookies['csrftoken'] File "\venv\lib\site-packages\requests\cookies.py", line 328, in __getitem__ return self._find_no_duplicates(name) File "\venv\lib\site-packages\requests\cookies.py", line 399, in _find_no_duplicates raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path)) KeyError: "name='csrftoken', domain=None, path=None" How to resolve this? Please comment for any other info. -
Django project "module markdown2 isnot found"
when i run python manage.py runserver in my project folder i get an error. like no module markdown2 I put import markdown2 top of my views.py file. Is anything else i need to do? anyone has any idea? thanks Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self.check(display_num_errors=True) File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/senayyakut/wiki/encyclopedia/urls.py", line 3, in <module> from . import views File "/Users/senayyakut/wiki/encyclopedia/views.py", line 1, in <module> import markdown2 ModuleNotFoundError: No module named 'markdown2'``` -
Best way to structure site files before going live
I have built a website using Django and I'm about to go live. I had a question about the structuring of CSS files before I publish. Currently my site looks like this -Root -App 1 -App 1 Files -App 2 -App 2 Files -App 3 -App 3 Files -mysite -Templates -App 1 Templates -App 2 Templates -App 3 Templates -Static -Images -CSS Files -JS My main css was quite large so I split it up into separate css files for each section. I'm wondering if it would make sense to place the css files next to their corresponding templates, or if it would be best to leave them in the static folder as they are now. Thank you! -
django.db.utils.IntegrityError: NOT NULL constraint failed: new__profiles_userprofile.email
How can I fix it , I simple want to add email_address in UserProfile model and it showing me this django.db.utils.IntegrityError: NOT NULL constraint failed: new__profiles_userprofile.email error when i try to migrate. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_address = models.EmailField(max_length=254,default=None,blank=True,null=True) follower = models.ManyToManyField(User, related_name ='is_following',blank=True,) close_friends = models.ManyToManyField(User,related_name='my_close_friends', blank=True) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) background =models.ImageField(("Background"), upload_to='backgrounds', default = 'ak.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) -
DRF asking for CSRF Token with TokenAuthentication as the only auth method
My only auth system for DRF is TokenAuthentication and it is still asking for a CSRF Token on a function based view. I'm not having this problem with class based views. settings.py: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication' ] } views.py: @api_view(['POST']) @authentication_classes([TokenAuthentication]) def submit_vote(request): # ... On Postman's POST request: Forbidden (CSRF cookie not set.): /rest/submit_vote/ [04/Nov/2020 02:05:38] "POST /rest/submit_vote/ HTTP/1.1" 403 2864 What?! I don't have any pending migration. -
How to exclude fields from Forms created from Models in Django?
Hello Stack Overflow Community, I am attempting to follow DRY principles and generate a form with a model I defined for tables in the database. Unfortunately it seems that createlistings.html prompts users to fill out Listed by, when it shouldn't be. How do I remove that? Also how can I fix this really ugly formatting or atleast make it not look like spaghetti? Will I need to do it through css or are there some basic defaults through Django? Thanks. Here is my Model definition from models.py: class AuctionListing(models.Model): CATEGORY_CHOICES = [ ... ] listing_title = models.CharField(max_length=64) image = models.ImageField(blank=True) image_url = models.URLField(blank=True) description = models.TextField(max_length=400) category = models.CharField( max_length=6, choices=CATEGORY_CHOICES ) starting_bid = models.DecimalField(max_digits=10, decimal_places=2, default=0) date_posted = models.TimeField(auto_now=True) # When the referenced object (User) is deleted, also delete the # objects (Auction Listings) that have references to it. listed_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="listings") def __str__(self): return f"{self.listing_title} ({self.category})." Here is my form definition in views.py: class CreateListing(ModelForm): class Meta: model = AuctionListing exclude = ('listing_by', 'listings', ) # listed_by is filled out in view Also, for readability is it good practice to import my CATEGORY_CHOICES from a different file if it's a really long list? -
How do i create a static file in django
Please how can I correct this errorenter image description here I keep getting errors connecting BASE_DIRS to my static files -
How to create profile update view without profile create view?
Here I am trying to create profile update view , i haven't use profile create view in my views.py because that i am creating profile by signals so , i dont need profile create view but i need update view so that user can update his profile, i am getting an error ValueError at /profiles/profiles/admin/1/ The view profiles.views.ProfileUpdateView didn't return an HttpResponse object. It returned None instead. i dont know to fix it, here below is my code , If you think i am doing in very unprofessional way than please let me know and tell me the more professional way to do this. views.py class ProfileUpdateView(UpdateView): refirect_field_name ='profiles:final_detail.html' form_class = UserUpdateForm model = UserProfile def get_context_data(self, *args, **kwargs): context = super(ProfileUpdateView, self).get_context_data(*args, **kwargs) update_form = UserUpdateForm(instance = self.request.user) context['form']=update_form return context def form_valid(self,form): form.save() urls.py app_name = 'profiles' urlpatterns = [ path('final/<str:username>/',FinalProfileDetailView.as_view(),name = 'final_detail'), path('profiles/<str:username>/<int:pk>/',ProfileUpdateView.as_view(),name = 'update'), ] model.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follower = models.ManyToManyField(User, related_name ='is_following',blank=True,) close_friends = models.ManyToManyField(User,related_name='my_close_friends', blank=True) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) background =models.ImageField(("Background"), upload_to='backgrounds', default = 'ak.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) objects = ProfileManager() def __str__(self): return f'{self.user.username}' def save(self,*args, **kwargs): super(UserProfile,self).save(*args, … -
Django manytomany field shows all existing objects of that type in the admin
The title covers most of it. I have a model Game with a manytomany field called users this field has blank=True because it can be empty. Whenever I open this object in the admin it shows a list of all existing users instead of the users that are added to this particular game object. If i print the users in my consumer it shows that it is empty (which it is). How can I make the admin show the user objects that are in the users field. -
Calling properties using "Self" keyword and One-To-Many Relationships in Django
I'm new to Django, and having some trouble understanding how the self keyword works, compared to this in JS or C#. I've been working through the [Django REST API tutorial][1], and now am trying to add a second Model class. I'd like to have a one-to-many relationship between each Snippet and SubSnippets, but would like to have my SubSnippets inherit the language and style properties of the parent Snippet so that I can use them in the formatter for each SubSnippet. Here's the code I've added to models.py: snippet = models.ForeignKey(Snippet, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) owner = models.ForeignKey('auth.User', related_name='sub-snippets', on_delete=models.CASCADE) highlighted = models.TextField() class Meta: ordering = ['snippet', 'created'] def save(self, *args, **kwargs): lexer = get_lexer_by_name(self.snippet.language) linenos = 'table' if self.linenos else False options = {'title': self.title} if self.title else {'snippet title': self.snippet.title} formatter = HtmlFormatter(style=self.snippet.style, linenos=linenos, full=True, **options) self.highlighted = highlight(self.code, lexer, formatter)``` The problem is that `self.snippet.language` doesn't seem to be calling the actual Snippet class, because I'm getting an error that says "Instance of ForeignKey has no 'language' member." Same with `self.snippet.title` and `self.snippet.style`. I find the convention of putting all Models in a single file … -
Django Datatables taking too long to load
I am trying to load 25600 rows into datatables but it's taking around 10 seconds. The request is via an ajax API call. views.py @api_view() def get_all_data(request): get_all_data_ = Data.objects.values("name","contact_number","email_address","address","age", "location_type","sector","phase","total_data","total_usage","city","district") return JsonResponse(list(get_all_data_), safe=False) template.html var table = $('#data-table').DataTable({ serverSide: true, "ajax": { "url": "/alldata/", "dataSrc": "" }, "columns": [ {"data": "name"}, {"data": "contact_number"}, {"data": "email_address"}, {"data": "address"}, {"data": "age"}, {"data": "location_type"}, {"data": "sector"}, {"data": "phase"}, {"data": "total_data"}, {"data": "total_usage"}, {"data": "city"}, {"data": "district"} ], }); How can i make it instantaneous? -
Django Template Display Context in Modal On Click
I may be completely going about this wrong, but fairly new to Django Templates and appreciate any help. I have a template that dynamically creates a table of rows of data based on context passed to the template from the view. html table rows being generated by loop <tbody> <!--Table Rows--> {% for ruleset in rulesets %} <tr> <th scope="row">{{ forloop.counter }}</th> <td><a href="{% url 'ruleset_detail' ruleset.id %}">{{ ruleset.ruleset_name }}</a></td> <td>{{ ruleset.ruleset_description }}</td> <td>{{ ruleset.ruleset_create_date|date:'m-d-Y' }}</td> <td style="text-align:center;">10</td> <td style="text-align:center;"> <div> <!-- EDIT modal button--> <button type="button" id="editRuleset" name="{{ ruleset.id }}" value="{{ ruleset.ruleset_name }}" class="btn btn-link align-middle" data-toggle="modal" data-target="#editRuleset"> <i class="fas fa-edit fa-sm"></i> <span style="font-size:small">EDIT</span> </button> </div> </td> </tr> {% endfor %} </tbody> the result is an EDIT button created for each row of data in the table with the rows ruleset id and name stored as the button name and value. When the user clicks on the EDIT button, a modal is displayed that should take the data from that row and assign it to the value of form inputs. modal form <form action="" method="PUT"> {% csrf_token %} <div class="modal-body"> <div class="form-group"> <div class="pt-2"> <label for="edit_ruleset_name">Ruleset Name</label> <input id="edit_ruleset_name" name="edit_ruleset_name" class="form-control" type="text" value="" required> </div> <div class="pt-4"> <label for="edit_ruleset_description">Ruleset … -
Value won't get updated in Calendar form using sessionStorage
I am importing a calendar widget using django. Previously it was working fine if I changed the date and refreshed the page the date automatically save the entered date value. However, when I added a maxdate to the widget on page reload it will only refresh to the maxdate value (today's date) and never get updated. options={ "format": "YYYY-MM-DD", # moment date-time format "calendarWeeks": True, "locale": "en-gb", "maxDate": datetime.datetime.today().strftime('%Y-%m-%d') })) My Solution: I figured I can solve this problem saving the value through sessionStorage and updating the value. My code works as intended but for some reason will not update my widget. My thought is the calendar widget maxdate is overriding my entered date. You can see below my value I inputted and the max date towards the end of the code line. Has anyone encountered this problem? Seems like my max date (today) will override my inputted 2020-09-07 value on page reload. <input type="text" name="Calendar" value="2020-09-07" class="form-control" id="id_Calendar" dp_config="{"id": "dp_65", "picker_type": "DATE", "linked_to": null, "options": {"showClose": true, "showClear": true, "showTodayButton": true, "format": "YYYY-MM-DD", "calendarWeeks": true, "locale": "en-gb", "maxDate": "2020-11-03"}}" My JS to handle sessionStorage $(document).ready(function() { let current_value = document.getElementById("id_Calendar").value; let new_value = sessionStorage.setItem("id_Calendar",current_value); var getItem = sessionStorage.getItem("id_Calendar"); if … -
django render_to_string not cares about python variables that's saved in database model
i have an text email template saved in database , and it is include some python variables , for example {{ company_name }} but when i use 'render_to_string' django function , it see the '{{ company_name }}' as a string not as a python variable , and here is my codes: 1- this the text which is saved in database : "" this is an email auto reply test from {{ company_name }} sales department, we will contact you as soon as possible . thank "" 2- and this is my view codes: email_info_object = Email_Auto_Reply.objects.get(EAR_department=Site_departments.objects.get(DEB_name=department)) email_body = email_info_object.EAR_body company_name = 'company name example ' render_context = { 'email_body':email_body, 'company_name':company_name, } email_body = render_to_string("staff/email_rendering/auto_reply_new_request.html", render_context) print(email_body) 3- and this is my 'staff/email_rendering/auto_reply_new_request.html' file. {% autoescape off %} {{ email_body|safe}} {% endautoescape %} 4- and this is the output of print : 00 8848 [04/Nov/2020 01:17:03] "GET /admin/jsi18n/ HTTP/1.1" 200 3187 [04/Nov/2020 01:17:08] "GET /submit_ticket/ HTTP/1.1" 200 5244 this is an email auto reply test from {{ company_name }} sales department, we will contact you as soon as possible . thank [04/Nov/2020 01:17:13] "POST /submit_ticket/ HTTP/1.1" 302 0 -
VCF file write into amazon S3 bucket django
I need to write(save) a VCard .vcf file to my amazon s3 bucket, but there has been problems. I have managed to save vcf file locally and then duplicate to s3 bucket. How I can store direclty into s3 bucket, btw just started using aws, hope you can help! I get data from my customer model database and this is my django view import ... import boto3 customer = Customer.objects.get(identifier=identifier) data = {} data['n'] = customer.first_name + ' ' + customer.last_name data['fn'] = customer.first_name + ' ' + customer.last_name data['tel'] = customer.phone data['email'] = customer.email vcard = vobject.readOne('\n'.join([f'{k}:{v}' for k, v in data.items()])) vcard.name = 'VCARD' vcard.useBegin = True vcard.prettyPrint() ############# WORKS BUT SAVES LOCALLY ############### # path = (settings.MEDIA_ROOT + 'customer.vcf') # with open(path, 'w', newline='') as f: # myfile = File(f) # myfile.write(vcard.serialize()) ############# WORKS BUT SAVES LOCALLY ############### ############# dublicates to bucket ############### s3 = boto3.resource('s3') BUCKET = "bucket" s3.Bucket(BUCKET).upload_file(path, 'customer.vcf') -
Should I host my django webapp for free if it will be used by 1000+ people
I have made a Django web app where students from my resident as a student will order food and other stuff since the shops are far from us, So probably the website will be used by 1000+ students, so it is possible for me to host it for free (Heroku etc.) or I will need a hosting plan from a company?, which company will you recommend? MY Website Screenshot -
Using Python Desktop app to use Django Authentication
I'm working on developing a Desktop App with Python 2.7, Postgres and trying to integrate Django. The app connects into a database to query data being added by an acquisiton gui.At some point i want to have a webpage also For the server side i choose Django since it have a pretty neat admin page and authentication system. I added my main django project settings on my gui project and have managed to authenticate my user, but i really want to my "client" log-in and for this I need a session. It have been hard working around this. I have tried several things Using the django log in method directly: This is a little bit hard since for doing i cant find a way to generate the request for it. I can get the user from the authentication but not the request. Using request : I created a view and url specific for the client to make a request so' that it recieve the usernaame and password and ran the log-in at the server but i recieve an error. This is maybe because i dont have a session, and dind find nothing def do_login(self, event): # import django # from … -
Problems after run: heroku run python manage.py migrate
While I was deployed my django app in heroku, I run: heroku run python3 manage.py migrate and I get this messahe in my console: File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax my manage.py file is actually: #!~/.virtualenvs/djangodev/bin/python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myApp3.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() When I run python => python3, the next message is displayed: Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
how to resolve 'ValidationError' object has no attribute 'strip' issue?
I want to add or raise a validation registration form but I get this error: 'ValidationError' object has no attribute 'strip' how can I skip it? I'm suffering from these issues please if you could tell me the correct way to validate the registration form after you solve this problem I'll be appreciated. Thank you in advance class SignUp(UserCreationForm): def __init__(self, *args, **kwargs): super(SignUp, self).__init__(*args, **kwargs) self.error_messages = { 'username_match': 'username is already exist', 'email_match': 'Email is already exist', 'password_mismatch': 'these two password isn\'t match try again' } email = forms.EmailField(required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) # password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) # password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'})) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'password1', 'password2', 'email'] def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): return forms.ValidationError( self.error_messages['email_match'], ) return email def clean_username(self): username = self.cleaned_data.get('username') if User.objects.filter(username=username).exists(): return forms.ValidationError( self.error_messages['username_match'], ) return username def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: return forms.ValidationError( self.error_messages['password_mismatch'], ) return password2 def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user views.py def register(request): form = SignUp(None) if request.method == 'POST': form = SignUp(request.POST) if form.is_valid(): form.save() return redirect('accounts:login') … -
How to render CharField (choices) in Django Admin limiting options from one base to another?
I have two fields in my database which are shown as lists in the DJANGO administration panel # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') coordenadasb = models.DecimalField(max_digits=5, decimal_places=2, default=0.0) longitud = models.DecimalField(max_digits=8, decimal_places=3, default=0.0) latitud = models.DecimalField(max_digits=8, decimal_places=3, default=0.0) AREA = [ ('FR', 'AREA 1'), ('SO', 'AREA 2'), ('JR', 'AREA 3'), ('SR', 'AREA 4'), ] area = models.CharField(max_length=50, choices=AREA, default='unknown') GRUPO = [ ('FR', 'group 11'), ('SO', 'group 12'), ('JR', 'group 21'), ('SR', 'group 22'), ('GR', 'group 31'), ('GR', 'group 32'), ] group = models.CharField(max_length=50, choices=GRUPO, default='unknown') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) I want to make that in the administration panel when choosing the item 'AREA 1' of the field "area" in the field "group" only the elements 'group 11' and 'group 12' are shown From what I guess I think that the procedure to achieve this would be modifying the administration template by adding a JS that modifies the values of the "group" field based on an event that listens for the changes of the "area" field. Would this be correct? Is there a way to perform the desired behavior without modifying the default Django … -
ModuleNotFoundError: No module named 'products'
I'm a newbie to Django. I'm following a tutorial where I should create a model class called products. This is what I've included in my models.py document inside my APP called Products: class Products (models.Model): title = models.TextField() description = models.TextField() price = models.TextField() Then I added the APP to INSTALLED APPS in my setting.py document: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #third party #own 'products', However, when I tried to run the following command on my terminal I get an error: (env) dcorreavi@dcorreavi src % python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/dcorreavi/Dev/trydjano/python-virtual-environments/env/lib/python3.8/site- packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/dcorreavi/Dev/trydjano/python-virtual-environments/env/lib/python3.8/site- packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/Users/dcorreavi/Dev/trydjano/python-virtual-environments/env/lib/python3.8/site- packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/dcorreavi/Dev/trydjano/python-virtual-environments/env/lib/python3.8/site- packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/Users/dcorreavi/Dev/trydjano/python-virtual-environments/env/lib/python3.8/site- packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'products' -
How to pass url domain into Django View
In a class based django view, how can you extract the current domain for use in the view? For example. If I was at 'http://example.com/myview/', is there a way to get 'example' in the view? Similar to how you can get kwargs passed in the url (self.kwargs['someArgument']). I've tried: class MyView(LoginRequiredMixin, UpdateView): model = Maintenance form_class = Maintenance_Perform_Form template_name = 'maintenancePerform.html' def form_valid(self, form): asset = Assets.objects.get(id = self.kwargs['assetID']) form.instance.completedBy = (self.request.user.first_name)+ " "+(self.request.user.last_name) form.instance.recordedBy = (self.request.user.first_name)+ " "+(self.request.user.last_name) form.instance.complete = True redirect_url = self.request.domain + '/maintenanceList' return redirect(redirect_url) But self.request only returns the url that is appended to the domain. I was hoping for 'example.com' Some additional context, because there may be a much easier way of accomplishing what I am trying to do... I have a Django application running on an internal corporate network only, and in the early stages of development the address to access the application was just the IP of the server 'http://10.0.0.1/myapp'. Our IT manager recently changed some settings so that you can access the server by name instead of IP, so you can now also use http://server-name.int/myapp. I added both of these to my ALLOWED_HOSTS in settings, but for some reason Django's loginrequiredmixin … -
django : create a unique ID for each modelForm submission
I have a modelForm in a template and I need to automatically create a ID for each row of the modelForm. The ID should be the same at each row, but unique per modelForm submission. Being somewhat a beginner in django, I am confused on how to achieve this. I have tried doing that: class historical_recent_data(models.Model): Description = models.CharField(max_length=200, default= ' ') Date = models.DateField() Quantity = models.FloatField(default=0) NetAmount = models.FloatField(default=0) id = models.AutoField(primary_key=True, serialize=True) customer_name = models.ForeignKey('Customer_base', on_delete=models.CASCADE, default="Unknown") invoice_number = models.CharField(max_length= 500, default=create_invoice_number) def __str__(self): return self.reference with this function to generate a unique value: def create_invoice_number(): last_invoice = invoice.objects.all().order_by('id').last() if not last_invoice: return 'INV001' invoice_no = last_invoice.invoice_number invoice_int = int(invoice_no.split('INV')[-1]) new_invoice_int = invoice_int + 1 new_invoice_no = 'INV' + str(new_invoice_int) return new_invoice_no and my view looks like that: def New_Sales(request): #context = {} form = modelformset_factory(historical_recent_data, fields=('Id', 'Description','Date','Quantity', 'NetAmount', 'customer_name', 'invoice_number')) if request.method == 'GET': formset = form(queryset= historical_recent_data.objects.none()) #blank_form = formset.empty_form elif request.method == 'POST': formset = form(request.POST) #invoice_hidden_form = CreateInvoiceForm(request.POST) #blank_form = formset.empty_form if formset.is_valid(): #request.session['sale'] = formset.cleaned_data for check_form in formset: check_form.save() quantity = check_form.cleaned_data.get('Quantity') id = check_form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') … -
Testing ImageField cropping for Django
This is my models.py: from PIL import Image from places.fields import PlacesField class ResourcePost(models.Model): dropoff_location = PlacesField(blank=True, null=True)= image = models.ImageField( default="donation-pics/default.jpg", upload_to="donation-pics", blank=True ) def save(self, *args, **kwargs): if not self.dropoff_location: self.dropoff_location = self.donor.donorprofile.dropoff_location super().save(*args, **kwargs) path = self.image.path img = Image.open(path) if img.height > 300 or img.width > 300: output_size = (300, 300) img = img.crop_to_aspect(300, 300) img.thumbnail(output_size) img.save(path) and this is my test.py @override_settings(MEDIA_ROOT=tempfile.gettempdir()) def test_image_crop(self): image = Image.new('RGB', (500, 500)) image_file = NamedTemporaryFile(suffix='.jpg') image.save(image_file) create_resource_post = ResourcePost( ... image = image_file, ... ) create_resource_post.save() height = create_resource_post.image.height width = create_resource_post.image.width self.assertEqual(height, 300) self.assertEqual(width, 300) I keep getting this error when I run the test: File "C:\Users\ccjgl\Desktop\SWEdjango\urban-thrifter\donation\tests.py", line 103 image = image_file, ^ SyntaxError: invalid syntax The editor shows me that image is a tuple and image_file is a string. I think that is the problem, but I don't know how to solve it. Question: How can I solve the syntaxError? Is it correct to use create_resource_post.image.height to access the image's size? -
AttributeError: '_io.BufferedReader' object has no attribute '_committed'
I am writing tests for my application. I have searched over the internet for the same error but I can't find anything. I had this error yesterday but then my deadline is very tight. Today I face the same error. It seems this error only occurs when I try to assign the user onetoone field twice to two different models. What's happening is that I am trying to create two different profiles. One profile is a seller profile and this other is a buyer profile. The code for the tests -> from django.test import TestCase, Client from django.urls import reverse from shop.models import Category, Product from users.models import Profile, User, SellerProfile class TestViews(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create_user( email='johndoe@gmail.com', password='secretpass203', username='johndoe', ) # Now log in the test client password = "secretpass203" self.is_authenticated = self.client.login( username=self.user.username, password=password) # Test if a user profile can be created successfully def test_user_profile_creation(self): url = reverse("users:create-profile") # Send a post request with open("test_data/profile.jpg", 'rb') as dp: response = self.client.post(url, { 'firstname': 'John', 'lastname': 'Doe', 'profile_picture': dp }) # assert the response returned if's it is a redirect self.assertEquals(response.status_code, 302) # Check if the profile was created self.assertEquals(Profile.objects.last().firstname, 'John') def test_user_is_logged_in(self): self.assertEquals(self.is_authenticated, …