Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django download file not found
I'm using Python 3.6 and django 2.2 to develop a webserver. I want to have a webpage displaying a download link for a file I generated based on user input. In my setting.py I have: MEDIA_ROOT = os.path.join.(BASE_DIR,'media') MEDIA_URL='/media/' In my views.py I have query.outputfile.name = os.path.join('submission',query_id,'output_file.txt') to associate the filefield object to the file that I created: path/to/project/media/submission/[query_id]/output_file.txt And when I include print(query.outputfile.url) I got: media/submission/[query_id]/output_file.txt In my html template I have <a href={{ query.outputfile.url }} download> Download output file here </a> On the webpage the file link points to [local ip]/media/submission/[query_id]/output_file.txt But when I click on the link chrome says "Failed - No file" and on the cmd line I got Not Found: /media/submission/[query_id]/output_file.txt I found related questions like this one but do not understand what's wrong with my code. My questions are: The .url seems to be relative to my MEDIA_ROOT, but why it cannot find my file? Does the cmd line error point to the absolute path /media/... ? I tried to make that path and file but still got the same error. What should I do to generate the download link? Thanks -
Is there a way of a inserting blank datetimefield from another table?
class Customer(models.Model): last_purchase = models.DateTimeField(blank=True, null=True) I have a blank DateTimeField, which will continuously update itself with the last modified DateTimeField in the corresponding table. class Order(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) How will this look on views? -
no such table: main.auth_user__old (OperationalError)
Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/main/tutorial/add/ Django Version: 2.1.4 Python Version: 3.8.2 Traceback: File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py" in execute 296. return Database.Cursor.execute(self, query, params) The above exception (no such table: main.auth_user__old) was the direct cause of the following exception: File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/options.py" in wrapper 604. return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/sites.py" in inner 223. return view(request, *args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/options.py" in add_view 1637. return self.changeform_view(request, None, form_url, extra_context) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/options.py" in changeform_view 1525. return self._changeform_view(request, object_id, form_url, extra_context) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/options.py" in _changeform_view 1568. self.log_addition(request, new_object, change_message) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/options.py" in log_addition 804. return LogEntry.objects.log_action( File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/models.py" in log_action 29. return self.model.objects.create( File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/models/query.py" in create 413. obj.save(force_insert=True, using=self.db) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/models/base.py" in save 717. self.save_base(using=using, force_insert=force_insert, File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/models/base.py" in save_base 748. updated = … -
How can I display images in Django after uploading?
I'm making a small blog. And I will be creating a cover image uploading system. But after uploading, I'm unable to retrieve the image. Do you have any solutions? Here's my model.py: class Post(models.Model): id = models.AutoField author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content_images = models.ImageField(default="media/noimg-l.jpg") and here's form.py: class Createcontent(forms.ModelForm): class Meta: model = Post fields = ( "title", "content", "slug", "content_images", "status", ) file = forms.FileField() widgets = { "content": SummernoteWidget(), } and this is the HTML I'm using: <div class="row"> <form method="POST" enctype="multipart/form-data" class="post-form">{% csrf_token %} {{ form|crispy }} <button type="submit" class="save btn btn-default">Save</button> </form> </div> and my setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') X_FRAME_OPTIONS = 'SAMEORIGIN' SUMMERNOTE_THEME = 'bs4' # Show summernote with Bootstrap4 -
Django... Why template page doesn't show results of the query in the view function
Sorry I am new to django and I made mistake or bunch of mistakes somewhere and I don't see what is wrong... Django also doesn't let me know where is the mistake... If somebody pinpoint me to the answer or let me know what is wrong that would be totally awesome... Thank you I have 2 models: one is the Director (pk = director_name) and one is the Worker (pk = worker_name)... Means family names, unique... They are many to many connection for the database. One worker can be under 2 supervisors... So, another model is Connection (fk = director_connect, fk = worker_connect, pk = (director_connect, worker_connect))... By the way, in postgresql the database model as I just described, but when I run "inspectdb" in cmd... it gives me: worker_connect = models.OneToOneField(...)// I made this connection by the alphabet, but somehow for Django, instead of ForeignKey it is OneToOneField? Can I just change it to models.ForeignKey(...)? And then apply changes? director_connect = models.ForeignKey(...) // as expected... def __str__(self): return f'{self.worker_connect}' def get_absolute_url(self): return reverse('director-detail', args=[str(self.director_connect)]) class Meta: managed=False db_table 'Connection' unique_together = (('director_connect', 'worker_connect')) ...So, the idea is to be able to find which worker under whose supervision, and whom … -
Is there a way to crop an image using only css? [duplicate]
I am currently working on a django project which is a youtube clone.I scrape the image of the thumbnails of the videos.When I do so, I faced a problem in fixing the image in the card(from materializecss).The image has empty black space on top and bottom.This is URL of a sample image:https://i.ytimg.com/vi/bt4-FwVe1Fk/hqdefault.jpg Now i want to crop the image so that, the empty black space doesn't show up.Is there a way to do it with only CSS?Any help would be appreciated. Thank You in advance. -
How to post multiple objects in Django Rest API from HTML form where multiple input filed id are same
Here You Can See My form where user Can give input and my goal is to take all the data user-provided and post it through API Firstly I want to see you my HTML code : <div class="content" id="skills"> <form action="#" method="post" class="job-post-form ajax" id="skill_create"> <div class="form-group row"> <label class="col-sm-3 col-form-label">Type Skills</label> <div class="col-sm-9"> <div class="input-group"> <div class="input-group-prepend"> <div class="input-group-text">01</div> </div> <select class="form-control" data-text="name" id="skill_name_id" data-value="id" data-placeholder="Skills" data-src="/api/skill_list"> </select> <input type="number" id="rating" class="form-control" placeholder="Rating"> <label class="form-control" >Verified By SkillCheck</label> <input type="checkbox" id="verified_by_skillcheck" style="margin-top:16px;" name="Skillcheck" value="X"> </div> </div> </div> <div class="form-group row"> <div class="offset-sm-3 col-sm-9"> <div class="input-group"> <div class="input-group-prepend"> <div class="input-group-text" >02</div> </div> <!-- <input type="text" class="form-control" >--> <select class="form-control" id="skill_name_id" data-text="name" data-value="id" data-placeholder="Skills" data-src="/api/skill_list"> </select> <input type="number" id="rating" class="form-control" placeholder="Rating"> <label class="form-control">Verified By SkillCheck</label> <input type="checkbox" id="verified_by_skillcheck" style="margin-top:16px;" name="Skillcheck" value="X"> </div> </div> </div> And now I will show you my script code : function skillGet(){ var skill_id = $("#skill_name_id").val(); var skill_rating = $("#rating").val(); var isVerified = $('input[name="Skillcheck"]:checked').val(); var path = window.location.pathname.split('/'); var id = path[path.length-2]; if (!isVerified){ isVerified = "False"; } else{ isVerified = "True"; } var data = { "professional_id" : id, "skill_name_id": skill_id, "rating": skill_rating, "verified_by_skillcheck": isVerified } skillCreateUrl = "/api/professional/professional_skill/"; if(Object.keys(data).length>1){ post(skillCreateUrl, JSON.stringify(data)); } } By this … -
How to get intermediary models instances related to a specific model in a Django symmetrical m2m relation?
Since Django 3.0, setting symmetrical=True for recursive m2m relationships using a through model is supported. [docs] For exemple, with the following models, where Town objects are symmetricaly linked together through Roads objects : class Town(models.Model): neighboors = models.ManyToManyField('self', through='Road', symetrical=True) class Road(models.Model): from_town = models.ForeignKey('Town', models.CASCADE, related_name='road_from') to_town = models.ForeignKey('Town', models.CASCADE, related_name='road_to') How to get all Road instances related to a specific town? As the doc explains, related_name of the two fk in the Road models have to be different, meaning a single reverse acessor like town.related_road will not work. Of course, I can set two different related_name and join the results of two queries, but that does not seems very Pythonic to me: class Town(models.Model): ... @property def roads(self): return self.road_to + self.road_from Is there any other way I can achieve this ? -
Why does Django create a new instance instead of update?
I want to modify some of my 'Location' object with an UpdateView. class LocationUpdateView(UpdateView): #form_class = LocationForm model = LocationTemplate fields = ['address','district','grid_x','grid_y'] #template_name = 'locationTemplate_update_form' def get_success_url(self): return reverse('location_detail', kwargs={'pk': self.object.pk}) def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): self.object = self.get_object() for loc in Location.objects.all(): if self.object.location_name == loc.location_name: setattr(loc,'address',(form.cleaned_data['address'])) setattr(loc,'district',(form.cleaned_data['district'])) setattr(loc,'grid_x',(form.cleaned_data['grid_x'])) setattr(loc,'grid_y',(form.cleaned_data['grid_y'])) loc.save() return self.form_valid(form) else: return self.form_invalid(form) However, instead of updating the objects, the above loop creates a new object with the update information(except the location_name is None). I was expecting setattr() to modify the attributes of that specific loc instead of creating new instances. models.py class LocationTemplate(models.Model): location_name = models.CharField(max_length=50, null=True, blank=True) address = models.CharField(max_length=300, null=True, blank=True) district = models.CharField(max_length=300, null=True, blank=True) grid_x = models.IntegerField(null=True, blank=True) grid_y = models.IntegerField(null=True, blank=True) def __str__(self): return self.location_name + ", Address: " + self.address + ", District: " + self.district + ", Coordinates: (" + str(self.grid_x) + ", " + str(self.grid_y) + ")" forms.py class LocationForm(forms.ModelForm): class Meta: model = LocationTemplate #exclude = ('patient',) fields=['location_name', 'address','district', 'grid_x','grid_y'] -
Rename files uploaded in Django admin and omit fields in the form
I'm using Django 3.0.5 and I want to upload images in the Django admin. I'm trying to: 1) change the filename uploaded the media folder based on the image data. 2) Omit fields in the displayed form because these are auto generated. The model is registered in admin.py This is my code in models.py: from django.db import models from hashlib import md5 from PIL import Image from io import BytesIO class NewImage(models.Model): image_name = models.CharField(max_length=255, default='') pub_date = models.DateTimeField(auto_now=True) image = models.ImageField(upload_to='images/') height = models.IntegerField(default=0) width = models.IntegerField(default=0) extension = models.CharField(max_length=20, null=False, default='') image_hash = models.CharField(max_length=50, null=False, unique=True, db_column='hash', default='') def __str__(self): return self.image_name @staticmethod def hash_exists(hash): return NewImage.objects.filter(image_hash=hash).exists() def generate_name(self): try: img_id = NewImage.objects.values('id').order_by('-id').first()['id'] + 1 except: img_id = 1 self.image_name = "%s_%s" % (img_id, self.image_hash[-4:]) def save(self, *args, **kwargs): img = Image.open(self.image) self.image_hash = md5(img.tobytes()).hexdigest() if not self.pk: try: if self.hash_exists(self.image_hash): raise ValueError("image hash already exists, duplicate image!") except ValueError as err: print(err.args) return "" self.width, self.height = img.size self.extension = img.format.lower() self.generate_name() super(NewImage, self).save(*args, **kwargs) 1) How can I have the file in the media folder be image_name 2) For omitting the fields. Based on SOF answers, I tried the following (it doesn't work) in forms.py: from … -
Why do i have this error message while migrating on django
Here's my models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField (max_lenght=2083) Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\dill\PycharmProjects\PyShop\venv\lib\site-packages\django\core\management\__init__.p y", line 401, in execute_from_command_line utility.execute() File "C:\Users\dill\PycharmProjects\PyShop\venv\lib\site-packages\django\core\management\__init__.p y", line 377, in execute django.setup() File "C:\Users\dill\PycharmProjects\PyShop\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\dill\PycharmProjects\PyShop\venv\lib\site-packages\django\apps\registry.py", line 11 4, in populate app_config.import_models() File "C:\Users\dill\PycharmProjects\PyShop\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\dill\AppData\Local\Programs\Python\Python37\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 680, in exec_module File "", line 219, in _call_with_frames_removed File "C:\Users\dill\PycharmProjects\PyShop\products\models.py", line 3, in class Product(models.Model): File "C:\Users\dill\PycharmProjects\PyShop\products\models.py", line 7, in Product image_url = models.CharField (max_lenght=2083) File "C:\Users\dill\PycharmProjects\PyShop\venv\lib\site-packages\django\db\models\fields__init__. py", line 984, in init super().init(*args, **kwargs) TypeError: init() got an unexpected keyword argument 'max_lenght' -
Accessing model attributes in Django
I'm trying to show users the product variations that they have selected. While the code is working and saving the variation in the database, I am not being able to show them on my html page. Only : is being rendered. If I try {{ order_item.variation.all }} and it gives an empty queryset like : <QuerySet []>. And if I try {{ order_item.variation }}, it says : products.Variation.None. What is the problem? Is the way I'm calling it wrong? This is what I've tried: My models.py: class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True, blank=True) variation_type = models.CharField(max_length=120, choices=VAR_TYPES, default='Size') title = models.CharField(max_length=120, null=True, blank=True) price = models.FloatField(null=True, blank=True) is_available = models.BooleanField(default=True) objects = VariationManager() class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) variation = models.ManyToManyField(Variation) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20) ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem) variation = models.ManyToManyField(Variation) My order_summary.html: {% for order_item in object.items.all %} <tbody> <tr> <th scope="row" class="border-0"> <div class="p-2"> <img src="{{ order_item.item.image_url }}" alt="" width="70" class="img-fluid rounded shadow-sm"> <div class="ml-3 d-inline-block align-middle"> <h5 class="mb-0"> <a href="{{ order_item.item.get_absolute_url }}" class="text-dark d-inline-block align-middle">{{ order_item.item.title }}</a> {% if order_item.variation %} <ul> <h6>{{ order_item.variation.variation_type }} : {{ … -
Django M2M how to set default reference in models
after User has been created I want User get default products by id, I must use def save(): func in models but dont know how to do it My models: class Product(models.Model): user = models.ManyToManyField(get_user_model() , blank=True) class User(AbstractBaseUser): first_name = models.CharField(max_length=254) -
Can I fully integrate Wagtail CMS with an Angular frontend?
So I was needing some kinda of CMS for my project and how I have experience with Django I was thinking of using Wagtail CMS. For example, let's say I'm doing some kinda of blog with Angular 9 as frontend, with user sign up, comments, contact forms and all that stuff. I was reading the Wagtail documentation and the "read_only" API had me worried, my question is simple: Can I fully integrate Wagtail CMS with an Angular frontend? With all the functionalities, because if I was using an API I would need POST, PATCH, etc... -
Sonar Cloud Security Hotspot for Django manage.py file
Sonar Analysis gives the following Security HotSpot in the manage.py file of my Django Project "Make sure that command line arguments are used safely here" On the following line execute_from_command_line(sys.argv) On the argv to be precise Any idea how I can fix this? -
How do i make a functioning Delete confirmation popup in Django using Bootstrap4 Modal
My views.py file looks like this. def deleteOrder(request, pk): order = Order.objects.get(id=pk) if request.method=="POST": order.delete() return redirect('/') context = {"item":order} return render(request, 'accounts/delete.html', context) My url.py file looks like this. urlpatterns = [ path('delete_order/<str:pk>', views.deleteOrder, name="delete_order"), ] Bootstrap Delete Popup i want to apply <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> My Home page which contain deleting row data for a table looks like this. <table class="table table-sm"> <tr> <th>Product</th> <th>Date Ordered</th> <th>Status</th> <th>Update</th> <th>Remove</th> </tr> {% for order in orders %} <tr> <td>{{ order.product }}</td> <td>{{ order.date_created }}</td> <td>{{ order.status }}</td> <td><a class="btn btn-sm btn-info" href="{% url 'update_order' order.id %}">Update</a></td> **<td><a class="btn btn-sm btn-danger" href="{% url 'delete_order' order.id %}">Delete</a></td>** </tr> {% endfor %} </table> The Line that i have added ** asterisks(intentionally) is the one i want to modify so that when i click on Delete button, a Bootstrap popup … -
How to pass django serializers Validation Error of a field to React as json fromat
In my rest framework user registration form I successfully created a custom registration form and added some validators. It shows corresponding validation errors in rest framework.but when linked this to react through redux it gets the error but not showing corresponding validation errors like " A user is already registered with this e-mail address. ". The rest showsit like this. JSON format that gets at react is this error: { message: 'Request failed with status code 400', name: 'Error', fileName: 'http://localhost:3000/static/js/1.chunk.js', lineNumber: 871, columnNumber: 15, stack: 'createError@http://localhost:3000/static/js/1.chunk.js:871:15\nsettle@http://localhost:3000/static/js/1.chunk.js:1092:12\nhandleLoad@http://localhost:3000/static/js/1.chunk.js:346:13\nEventHandlerNonNull*dispatchXhrRequest@http://localhost:3000/static/js/1.chunk.js:322:5\nxhrAdapter@http://localhost:3000/static/js/1.chunk.js:301:10\ndispatchRequest@http://localhost:3000/static/js/1.chunk.js:924:10\npromise callback*request@http://localhost:3000/static/js/1.chunk.js:712:23\nforEachMethodWithData/Axios.prototype[method]@http://localhost:3000/static/js/1.chunk.js:736:17\nwrap@http://localhost:3000/static/js/1.chunk.js:1252:15\nsignUp/<@http://localhost:3000/static/js/main.chunk.js:3406:50\ncreateThunkMiddleware/</</<@http://localhost:3000/static/js/1.chunk.js:40096:18\ndispatch@http://localhost:3000/register:1:28546\nonAuth@http://localhost:3000/static/js/main.chunk.js:3305:110\nRegMain/this.handlesubmit@http://localhost:3000/static/js/main.chunk.js:2684:62\ncallCallback@http://localhost:3000/static/js/1.chunk.js:8030:18\ninvokeGuardedCallbackDev@http://localhost:3000/static/js/1.chunk.js:8079:20\ninvokeGuardedCallback@http://localhost:3000/static/js/1.chunk.js:8132:35\ninvokeGuardedCallbackAndCatchFirstError@http://localhost:3000/static/js/1.chunk.js:8147:29\nexecuteDispatch@http://localhost:3000/static/js/1.chunk.js:8232:46\nexecuteDispatchesInOrder@http://localhost:3000/static/js/1.chunk.js:8257:24\nexecuteDispatchesAndRelease@http://localhost:3000/static/js/1.chunk.js:11141:33\nexecuteDispatchesAndReleaseTopLevel@http://localhost:3000/static/js/1.chunk.js:11150:14\nforEachAccumulated@http://localhost:3000/static/js/1.chunk.js:11122:12\nrunEventsInBatch@http://localhost:3000/static/js/1.chunk.js:11167:25\nrunExtractedPluginEventsInBatch@http://localhost:3000/static/js/1.chunk.js:11377:23\nhandleTopLevel@http://localhost:3000/static/js/1.chunk.js:11421:40\nbatchedEventUpdates$1@http://localhost:3000/static/js/1.chunk.js:29567:16\nbatchedEventUpdates@http://localhost:3000/static/js/1.chunk.js:8639:16\ndispatchEventForLegacyPluginEventSystem@http://localhost:3000/static/js/1.chunk.js:11431:28\nattemptToDispatchEvent@http://localhost:3000/static/js/1.chunk.js:12151:48\ndispatchEvent@http://localhost:3000/static/js/1.chunk.js:12072:45\nunstable_runWithPriority@http://localhost:3000/static/js/1.chunk.js:41893:16\nrunWithPriority$1@http://localhost:3000/static/js/1.chunk.js:18917:14\ndiscreteUpdates$1@http://localhost:3000/static/js/1.chunk.js:29584:16\ndiscreteUpdates@http://localhost:3000/static/js/1.chunk.js:8652:16\ndispatchDiscreteEvent@http://localhost:3000/static/js/1.chunk.js:12051:22\nEventListener.handleEvent*addEventBubbleListener@http://localhost:3000/static/js/1.chunk.js:11905:15\ntrapEventForPluginEventSystem@http://localhost:3000/static/js/1.chunk.js:12045:31\ntrapBubbledEvent@http://localhost:3000/static/js/1.chunk.js:12015:36\nsetInitialProperties@http://localhost:3000/static/js/1.chunk.js:13826:27\nfinalizeInitialChildren@http://localhost:3000/static/js/1.chunk.js:15351:27\ncompleteWork@http://localhost:3000/static/js/1.chunk.js:26705:44\ncompleteUnitOfWork@http://localhost:3000/static/js/1.chunk.js:29895:20\nperformUnitOfWork@http://localhost:3000/static/js/1.chunk.js:29868:16\nworkLoopSync@http://localhost:3000/static/js/1.chunk.js:29833:26\nperformSyncWorkOnRoot@http://localhost:3000/static/js/1.chunk.js:29451:13\nscheduleUpdateOnFiber@http://localhost:3000/static/js/1.chunk.js:28883:32\nupdateContainer@http://localhost:3000/static/js/1.chunk.js:32032:19\nlegacyRenderSubtreeIntoContainer/<@http://localhost:3000/static/js/1.chunk.js:32415:26\nunbatchedUpdates@http://localhost:3000/static/js/1.chunk.js:29601:16\nlegacyRenderSubtreeIntoContainer@http://localhost:3000/static/js/1.chunk.js:32414:25\nrender@http://localhost:3000/static/js/1.chunk.js:32497:14\n./src/index.js@http://localhost:3000/static/js/main.chunk.js:4166:50\n__webpack_require__@http://localhost:3000/static/js/bundle.js:785:30\nfn@http://localhost:3000/static/js/bundle.js:151:20\n1@http://localhost:3000/static/js/main.chunk.js:4181:18\n__webpack_require__@http://localhost:3000/static/js/bundle.js:785:30\ncheckDeferredModules@http://localhost:3000/static/js/bundle.js:46:23\nwebpackJsonpCallback@http://localhost:3000/static/js/bundle.js:33:19\n@http://localhost:3000/static/js/main.chunk.js:1:71\n', config: { url: 'http://127.0.0.1:8000/rest-auth/register/', method: 'post', data: '{"fname":"Abhiram","lname":"PS","username":"rooteeee","phone":"8589967868","email":"abhirampjayan@outlook.com","cemail":"abhirampjayan@outlook.com","password1":"abhi1998","password2":"abhi1998","gender":"M","acctype":"Student"}', headers: { Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json;charset=utf-8' }, transformRequest: [ null ], transformResponse: [ null ], timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1 } } source code of serializer.py is given bellow from rest_framework import serializers from accounts.models import Account from allauth.account import app_settings as allauth_settings from allauth.utils import email_address_exists from allauth.account.adapter import get_adapter from allauth.account.utils import setup_user_email from rest_framework.validators import UniqueValidator from rest_framework.response import Response from rest_framework import status class CustomUserDetailsSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ('pk','email','fname','lname','username','phone','gender','acctype') #read_only_fields = ('email','acctype','fname','lname') class CustomRegisterSerializer(serializers.Serializer): fname = serializers.CharField(required=True, write_only=True) lname = serializers.CharField(required=True, write_only=True) username = serializers.CharField(min_length=allauth_settings.USERNAME_MIN_LENGTH,required=allauth_settings.USERNAME_REQUIRED,validators=[UniqueValidator(queryset=Account.objects.all(),message='A user is already registered with this … -
pytest-django: users created with create_user are always authenticated
I'm trying to write a fixture to generate Django users from custom user model. The weird thing is that the newly created user results authenticated by default, while I expect it to be anonymous. What am I doing wrong? Fixture: import pytest @pytest.fixture def create_user(db, django_user_model): def make_user(**kwargs): return django_user_model.objects.create_user(**kwargs) return make_user Test the fixture: @pytest.mark.django_db def test_fixture_create_user(create_user): user = create_user(user={'email': 'foo@bar.com', 'password': 'bar'}) assert user.is_authenticated is True # <-- this should be False but it's True assert user.is_anonymous is True # <-- this fails The test fails this way: E assert False is True E + where False = <CustomUser: foo@bar.com>.is_anonymous -
Unhandled Rejection (TypeError): this.state.persons.map is not a function
I am buildig a website using react and django but i seem to be stuck here. i have checked the net for solutions but i cannot seem to find one here is my code and the error i get. Uncaught TypeError: this.state.persons.map is not a function import React from "react"; import axios from "axios"; import { Container, Dimmer, Image, Item, Label, Loader, Message, Segment } from "semantic-ui-react"; import { productListURL } from "../constants"; export default class ProductList extends React.Component { state = { persons:[] }; componentDidMount(){ axios.get(productListURL) .then(res =>{ const persons = res.data; this.setState({persons}); }) } render(){ return ( <ul> {this.state.persons.map(person => <li>{person.title}</li>)} </ul> ) } } -
Div exceeding max width and fixed position
I'm working with a product page and currently trying to make it responsive. I have a button wrapper that shows when visiting the website with a mobile device. This wrapper is like the one in Hermes website (also switch to mobile), where the 'buy' button has a fixed position. This is the css: @media screen and (max-width:640px){ *{ max-width: 100%; } (...) .button-wrapper{ transform: translateY(0); display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; align-items: baseline; justify-items: center; padding: 2rem; z-index: 99; bottom: 0; left: 0; right: 0; justify-content: center; align-content: center; position: fixed; width: 100%; max-width: 100%; background-color: #f4f5fc; } Somehow, the container is bigger than the width of the device, which leaves a really akward space. Here's what I mean: Another problem is that the inicial position of the wrapper is below the height of the screen. The foto from above isn't cropped, and as you can see, the button is half-way there. But when I scroll down, this happens: Now the whole wrapper can be seen. Any help is appreciated! Thanks in advance. EDIT: This is the HTML: <body> {% include 'loader.html' %} <header> <div class="d-flex justify-content-center"> <div class="row"> <div class="responsive-logo"></div> <div class="pullcontainer"> <a href="#" id="pull"><i class="fa fa-bars fa-2x"></i></a> </div> … -
Django Problem: Unable to import 'django.db'
I am following this Django Polls App Documentation to learn Django and I ran into this error saying Unable to import 'django.db' in my virtual environment. This entry on stack overflow led me to this visual studio documentation on virtual environments which did not work for me. UsingPython: Select Interpreterto select an environment did not solve my problem since Python 3.8.2 64-bit *'env': venv was NOT available for me as seen from this image. Only the Python 2.7.17 64-bit ('polling-website': venv) option was available. The status bar image shows that I am running on Python 3.8.2 64-bit version. Knowing that this is a virtual environment issue, I'm wondering if I installed the virtual environment correctly. I installed my virtual environment using the command python3 -m venv. My virtual environment appears to be working fine as seen from the terminal below. The environment was activated properly and the python manage.py runserver command ran properly and I was able to successfully open the server. TERMINAL PS D:\User\Documents\CODE\polling-website> Scripts/activate (polling-website) PS D:\User\Documents\CODE\polling-website> cd mysite (polling-website) PS D:\User\Documents\CODE\polling-website\mysite> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 04, 2020 - 22:59:42 Django version … -
Cannot assign "8": "Comment.post" must be a "Post" instance
I can access a post using its ID or a slugified version of its title. Both localhost:8000/post/working-in-malaysia and localhost:8000/post/8 load the post called Working in Malaysia. I want users to be able to comment on any post. The comments load with the code comments = Comment.objects.filter(post=post.id ,active=True) When I manually select the value for the Post field, the comments are saved to the sites database. But I want the value for the Post field to be automatically populated. Based on the current post being displayed. I have tried new_comment.post = post.id and new_comment.post = post.title. views.py if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post.id new_comment.save() else: comment_form = CommentForm() urls.py urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<slug:pk_slug>/', views.post_detail, name='post-detail'), #path('post/<slug:the_slug>/', views.post_detail, name='post-detail'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name='blog-about'), #path('your-name/', views.about2, name='blog-about'), path('facebook/',TemplateView.as_view(template_name='blog/index.html'), name="facebook") ] -
counting problem in django blog: using ajax
i created a like button for my django blog using ajax but i'm getting an error that its not counting properly, at first its 0 like in a post when i hit like it works 1 like appeared with unlike button but when i hit unlike and like again it gives 2 likes and sometimes when i unlike it show -1 like i think its jquerry problem i'm not expert in jquerry jquerry code $(document).ready(function(){ function updateText(btn, newCount, verb){ btn.text(newCount + " " + verb) } $(".like-btn").click(function(e){ e.preventDefault() var this_ = $(this) var likeUrl = this_.attr("data-href") var likeCount = parseInt(this_.attr("data-likes")) |0 var addLike = likeCount + 1 var removeLike = likeCount - 1 if (likeUrl){ $.ajax({ url: likeUrl, method: "GET", data: {}, success: function(data){ console.log(data) var newLikes; if (data.liked){ updateText(this_, addLike, "Unlike") } else { updateText(this_, removeLike, "Like") // remove one like } }, error: function(error){ console.log(error) console.log("error") } }) } }) }) #post_details.html {% if user not in post.likes.all %} <p><a class='like-btn' data-href='{{ object.get_api_like_url }}' data-likes='{{ object.likes.all.count }}' href='{{ object.get_like_url }}'> {{ object.likes.all.count }} Like</a></p> {% else %} <p><a class='like-btn' data-href='{{ object.get_api_like_url }}' data-likes='{{ object.likes.all.count }}' href='{{ object.get_like_url }}'> {{ object.likes.all.count }} Unlike</a></p> {% endif %} view.py class PostLikeToggle(RedirectView): … -
ValueError: The view create.views.CheckoutView didn't return an HttpResponse object. It returned None instead
I am getting a ValueError that the class below didn't return any httpresponse when i try to redirect to a template. the redirect is supposed to go to the stripe payment view. here is an entire class that has the redirect call class CheckoutView(View): def get(self, *args, **kwargs): form = forms.CheckoutForm() context = { 'form': form } return render(self.request, "checkout.html", context) def post(self, *args, **kwargs): form = forms.CheckoutForm(self.request.POST or None) try: equipment_order = models.EquipmentOrder.objects.get(user=self.request.user, ordered=False) if form.is_valid(): street_address = form.cleaned_data.get('street_address') apartment_address = form.cleaned_data.get('apartment_address') country = form.cleaned_data.get('country') zip = form.cleaned_data.get('zip') ''' TODO: add functionality to these fields same_shipping_address = form.cleaned_data.get('same_shipping_address') save_info = form.cleaned_data.get('save_info') ''' payment_option = form.cleaned_data.get('payment_option') billing_address = models.BillingAddress( user=self.request.user, street_address=street_address, apartment_address=apartment_address, country=country, zip=zip ) billing_address.save() equipment_order.billing_address = billing_address equipment_order.save() if payment_option == 'S': return redirect('create:payment', payment_option='stripe') elif payment_option == 'P': return redirect('create:payment', payment_option='paypal') else: messages.warning(self.request, "Invalid payment option") return redirect('create:checkout') except ObjectDoesNotExist: messages.error(self.request, "You do not have an active order") return redirect("create:order_summary") -
Django_Filters and queryset
Hi guys I'm building a simple django website where the user can look for long play. The problem right now is that I can't figure out why the filter, built with the django_filters library, doesn't work. If you type "Queen" in the search bar in the home you are redirected to the searches.html where are listed all the LPs by Queen (just 4). On the left there's a filter. If you type "kind" in the form and submit then you should just see the album "Kind of Magic". This doesn't work. And I think the problem is the queryset "sp": class searchesView(TemplateView): template_name = "search/searches.html" def post(self, request, *args, **kwargs): print('FORM POSTED WITH {}'.format(request.POST['srh'])) srch = request.POST.get('srh') if srch: sp = Info.objects.filter(Q(band__icontains=srch)) | Info.objects.filter(Q(disco__icontains=srch)) myFilter = InfoFilter(request.GET, queryset=sp) sp = myFilter.qs paginator = Paginator(sp, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(self.request, 'search/searches.html', {'sp':sp, 'myFilter':myFilter, 'page_obj': page_obj }) else: return render(self.request, 'search/searches.html') I think the problem is the queryset because then I tried to build a result.html page where I listed all the LPs in the database and applied the same filter above and here it works perfectly: def result(request): result = Info.objects.all() myFilter = InfoFilter(request.GET, queryset=result) result = …