Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Return a Http Response In get_queryset
Im using get_queryset, in ListAPIView I want to check the user's access token, before providing the list, I done the below but the issue is that get_query set does not return a Response, is there a way to return a response, or I should use an alternative : this my class in the views.py : class ListProductsOfCategory(generics.ListAPIView): serializer_class = ProductSerializer lookup_url_kwarg = 'category_id' def get_queryset(self): # I get the token here from the headers token = self.request.META.get("HTTP_TOKEN", "") if not token: return Response( data={ "message": "no token!" }, status=status.HTTP_400_BAD_REQUEST ) if not UserAccess.objects.filter(accessToken=token).exists(): return Response( data={ "message": "invalid token!" }, status=status.HTTP_400_BAD_REQUEST ) category_id = self.kwargs.get(self.lookup_url_kwarg) return Product.objects.filter(category_id=category_id) note that everything is working perfect If I removed the token related part. thanks in advance. -
How to save data from a tuple objet in Python?
I am facing this error: AttributeError: 'tuple' object has no attribute 'save' from the following piece of code: def load_images_to_db(path): for dirname, dirnames, filenames in os.walk(path): for subdirname in dirnames: subject_path = os.path.join(dirname, subdirname) label = Label.get_or_create(name=subdirname) label.save() The error comes from this line: label.save() Someone can help ? -
Django one page website with lateral navbar
My current setup looks like this(from here, mostly): This is the result of my home view. What i intend on doing is keep those 2 sidebars in place and refresh only the content part. My question: What is the obvious solution to this in django? From what i read so far it seems to be using Ajax to see what exactly the user clicks on the sidebars and return only a part of the html which would be the div where all the content is. (or return a json and refresh that div depening on the json values?) I need to avoid refreshing the entire page, it seems useless. I could forget about Ajax and just run on separate views but i would have to pass every time a context variable to populate the sidebars depending on the user and this seems to me an overkill. -
Allow users to download files directly django
models.py : class TrainerProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='trainer_profile') profile_picture = models.ImageField(blank=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") mobile_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) location = models.CharField(max_length=200,null=True,blank=True) gender = models.CharField(choices=GENDER_CHOICES,max_length=150, blank=True) cv = models.FileField(blank=True) approval=models.BooleanField(default=False) def __str__(self): return self.user.username In my template: <li class="list-group-item"> <b>Download CV</b> <a class="pull-right">{{ trainer.cv }}</a> </li> In the TrainerProfileModel ,I have file field called cv . I want to allow users to download the file directly when clicking on the link.Any ways to implement this? -
Django error: Value too long for type character varying(2)
I did a database flush to reset my database. I am getting this error when I try to do the following code. Code that throws error: try: print("Attempting to load %s" % store.get('name')) # THIS NEXT LINE THROWS ERROR store_obj = Store.objects.get(name=store.get('name')) except Store.DoesNotExist: store_obj = Store(name=store.get('name'), last_updated=last_updated, address=store.get('address'), city=store.get('city'), state=store.get('state'), zip_code=store.get('zip_code')) Error: Exception Type: DataError at /stores/ Exception Value: value too long for type character varying(2) \d of stores_store Model in django: class Store(models.Model): name = models.CharField(max_length=200) description = models.TextField() created_at = models.DateTimeField(default=datetime.now, blank=True) last_updated = models.DateTimeField(default=datetime.now, blank=True) # Address address = models.CharField(_("address"), max_length=128) city = models.CharField(_("city"), max_length=128) state = USStateField(_("state")) zip_code = USZipCodeField(_("zip code"), max_length=5) def __str__(self): return self.name As you can see the store name is a VARCHAR of 200, not 2. However, I cannot complete this get operation without getting this error. I tried another flush and makemigrations -> migrate but still have no luck. What else can I try? Thanks! -
Django JQuery datatable ajax refresh - missing sorting buttons and inactive function calls
I'm running Django and using JQuery and jquery-datatables-bs3 to create a table for my models. The user can add and remove table rows, which corresponds to model instances being created or deleted in the database. Each row has an "actions" column containing a clickable function call. I'm using an ajax call to refresh the table after each user modification. table.html (context: {'entities': entities, 'display_fields': display_fields }) <table class="table table-bordered table-striped" id="datatable-editable"> <thead> <tr> {% for key in display_fields.keys %} <th>{{ key }}</th> {% endfor %} <th>Actions</th> </tr> </thead> <tbody> {% for entity in entities %} <tr> {% for key, value in entity.display_fields.items %} <td>{{ value }}</td> {% endfor %} <td class="actions"> <a href="#" class="locker"></a> </td> </tr> {% endfor %} </tbody> </table> The result: The table works properly. The sorting and clickable action call work fine. No problems so far. On refresh: update.js (ajax call on table modification) function refresh_table() { $.ajax({ url: '/refresh/url/', success: function(data) { $('#datatable-editable').html(data); } }); } The refresh works, the table is re-populated with data. However, once refreshed, the table is missing its header sorting buttons and the action function calls do not work anymore, even though the table's HTML is the same: update.js ("locker" class … -
Getting error in connecting firebase using django push notifications
Getting error, "Uncaught (in promise) ReferenceError: requestPOSTToServer is not defined"click to see Image/ screenshot -
How take modal as data type for field of another modal in Django?
Here I have Seller modal which contains the contact field. I created a new model name as Contact which has fields contact_number and address. I can simply give a foreign key to the contact field of Seller model to Contact model. But here I want to use the Contact model as a new data type for the contact field of Seller model. class Contact(models.Model): contact_number = PhoneNumberField(blank=False, null=False) address = models.TextField(blank=False, null=False) def __str__(self): return "%s" % self.name class Seller(models.Model): company_name = models.CharField(max_length=300, blank=False, null=False) company_profile = models.TextField(blank=False, null=False) contact = Contact() #Here I want use Contact model as data type for the contact field def __str__(self): return "%s" % self.company_name Is this possible? If yes Can anyone please Guide me for that. I am New in Django, I only have basic knowledge of Django. Here I am using PostgreSQL as a database. -
Django-scheduler finding the Views
Played around with django-scheduler-sample https://github.com/llazzaro/django-scheduler-sample and set it up for my new project. Now I tried to simply copy it into my django-project, which leads to several problems. I couldn't find any Views in it. It only has this include-code in the urls.py: url(r'^$', TemplateView.as_view(template_name="homepage.html"),), url(r'^schedule/', include('schedule.urls')), url(r'^admin/', admin.site.urls), I changed it into: path('calendarHome', TemplateView.as_view(template_name="homepage.html"),), path('schedule/', include('schedule.urls')), path('', admin.site.urls), So my question is, how to find the "Master"-File where all the commands come for the DB and the Views. Hope someone has some experience with this django-scheduler and give me a hint. -
under same username I can not post?
I am using Django 2.07. In my application after posting the first post, the second post it is not taking a post under the same username (I'm using Django all-auth). At Django admin, it shows me "this username already exits." this is my profile model: class Profile(models.Model): PUBLIC = 'Public' PRIVATE = 'Private' INITIATIVE ='Initiative' PRIVATE_STARTUP = 'Private and Startup' INITIAL_KEYWORD = ( (PUBLIC, 'Public'), (PRIVATE, 'Private'), (INITIATIVE, 'Initiative'), (PRIVATE_STARTUP, 'Private and Startup'), ) Type_of_account = models. NullBooleanField('Personal account', help_text="by default this is Business account") user_photo = models.ImageField(upload_to='user_image', blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE, default=1) occupation = models.CharField(max_length=400, null=False) name = models.CharField(max_length=200, null=False, blank=False, default=None) title = models.CharField(max_length=100, null=True, blank=True) url = models.URLField(max_length=200, null=True, blank=True) additional_url = models.URLField(max_length=200, null=True, blank=True ) Headquarter = models.CharField(max_length=1000, null=True, blank=True) stock_market = models.CharField(max_length=200, null=True, blank=True) established = models.DateField(auto_now=False, auto_now_add=False, default=None) investors = RichTextField(null=True, blank=True) about_details = RichTextField(null=False, blank=False, default=None) Type_of_company = models.CharField( max_length=20, null=True, blank=True, choices=INITIAL_KEYWORD, default=PRIVATE_STARTUP) This is my main-model. class MainModel(models.Model): I_THINK = 'I think' GOOD_PART = 'Good part' BAD_PART ='Bad part' PROTOTYPE = 'Prototype' FEEDBACK = 'Feedback' INFO = 'Info' REVIEW = 'Review' ASK = 'Ask' FINACIAL_MARKET = 'Financial market' INITIAL_KEYWORD_FOR_THOUGHTS = ( (I_THINK, 'I THINK'), (FEEDBACK, 'FEEDBACK'), (GOOD_PART, 'GOOD PART'), (BAD_PART, … -
Post video to Facebook Page with Facebook SDK
I'd like to post a video from url to my Facebook page. Is there any way for it, I already be able to post Images but seems like it's no way for video? Thanks in advanced^ -
How to properly write a url in django (trailing slash?)
What is the correct way to write a url: path('user/avatar', views.change_avatar, name='change_avatar'), or: path('user/avatar/', views.change_avatar, name='change_avatar'), I've seen it written both ways but I wasn't sure which was the suggested practice and why. -
Django: cannot render uploaded image in template
I've created a model that accepts any kind of file using FileField() in my model. I've uploaded correctly some files and saved the reference in the db, as I can see in the admin interface, and in the folder "media". However, cannot render this images in the template. I need to render it so my users will be able to download them to their computer. These are the paths to my images: media/imagenes/468x60.jpg #relative path /home/ogonzales/Escritorio/web_proyects/gallito/media/imagenes/468x60.jpg #full path Project structure gallito (Django project folder) |_gallito |_main_app |_static |_templates |_main_app |_pedidos.html |_media |_imagenes |_468x60.jpg |_728x90.jpg |_templates |_registration |_login.html |_base.html models.py: class TamaniosCantidades(models.Model): TAMANIOS = (('2x2', '2" x 2"',), ('3x3', '3" x 3"',), ('4x4', '4" x 4"',), ('5x5', '5" x 5"',)) CANTIDADES = (('50', '50',), ('100', '100',), ('150', '150',)) tamanios = models.CharField(max_length=10, choices=TAMANIOS) cantidades = models.CharField(max_length=10, choices=CANTIDADES) imagenes = models.FileField(upload_to='imagenes/') uploaded_at = models.DateTimeField(auto_now_add=True) forms.py: class TamaniosCantidadesForm(forms.ModelForm): tamanios = forms.ChoiceField(choices=TAMANIOS, widget=forms.RadioSelect(), label='Selecciona un tamaño') cantidades = forms.ChoiceField(choices=CANTIDADES, widget=forms.RadioSelect(), label='Selecciona la cantidad') class Meta: model = TamaniosCantidades # fields = ['tamanios', 'cantidades',] fields = ['tamanios', 'cantidades', 'imagenes'] views.py: def pedidos(request): pedidos = TamaniosCantidades.objects.all() return render(request, 'main_app/pedidos.html', {'pedidos': pedidos}) urls.py: urlpatterns = [ path('', views.index), path('productos/', views.productos), path('productos/die-cut-stickers', views.die_cut, name='die-cut-stickers'), path('post_url/', views.post_treasure, name='post_treasure'), path('post_url_tamanioscantidades/', views.post_tamanioscantidades, … -
Django database settings SERVER keyword SQL Server
I'm getting an error after installing the Microsoft Database driver for linux/ unix. Django is throwing this error: Neither DSN nor SERVER keyword supplied Is there a way to pass in the SERVER and DSN to the settings.py file to get the connection string Django creates to be properly configured? -
Django ManyToManyField initial
MamyToManyField not autofilling. I attempted all variants from here and here. But they are not working. My Model: class MyUser(AbstractBaseUser): email = models.EmailField(max_length=100, unique=True) class Order(models.Model): user = models.ManyToManyField(MyUser) quantity = models.PositiveIntegerField(default=1) My forms: class OrderForm(forms.ModelForm): user = forms.ModelMultipleChoiceField(queryset=None, to_field_name='email') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['user'].queryset = MyUser.objects.all() My views: def product_order(request, id): if request.method == 'POST': form = OrderForm(request.POST or None, initial={'user': request.user.email}) if form.is_valid(): new_form = form.save() return HttpResponseRedirect('/shop/') else: form = OrderForm() return render(request, 'shop/product_detail.html', locals()) -
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value
enter image description here enter image description here this is my settings in Django if start "python manage.py createsuperuser" and "python manage.py migrate" Print me a message from terminal Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/root/.pyenv/versions/bbgo2/lib/python3.6/site-packages/django/core/management/init.py", line 364, in execute_from_command_line utility.execute() File "/root/.pyenv/versions/bbgo2/lib/python3.6/site-packages/django/core/management/init.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/.pyenv/versions/bbgo2/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/root/.pyenv/versions/bbgo2/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/root/.pyenv/versions/bbgo2/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 110, in handle loader.check_consistent_history(connection) File "/root/.pyenv/versions/bbgo2/lib/python3.6/site-packages/django/db/migrations/loader.py", line 282, in check_consistent_history applied = recorder.applied_migrations() File "/root/.pyenv/versions/bbgo2/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/root/.pyenv/versions/bbgo2/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/root/.pyenv/versions/bbgo2/lib/python3.6/site-packages/django/db/backends/base/base.py", line 254, in cursor return self._cursor() File "/root/.pyenv/versions/bbgo2/lib/python3.6/site-packages/django/db/backends/base/base.py", line 229, in _cursor self.ensure_connection() File "/root/.pyenv/versions/bbgo2/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/root/.pyenv/versions/bbgo2/lib/python3.6/site-packages/django/db/backends/base/base.py", line 188, in connect conn_params = self.get_connection_params() File "/root/.pyenv/versions/bbgo2/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 158, in get_connection_params "settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value. (bbgo2) root@geoGroup:/bbgo# python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/root/.pyenv/versions/bbgo2/lib/python3.6/site-packages/django/core/management/init.py", line 364, in execute_from_command_line utility.execute() File "/root/.pyenv/versions/bbgo2/lib/python3.6/site-packages/django/core/management/init.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/.pyenv/versions/bbgo2/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/root/.pyenv/versions/bbgo2/lib/python3.6/site-packages/django/core/management/base.py", line 330, in … -
creating a view.py for comments
i'm trying to create a commment system where individual can be able to comment to a particular post, and drafting my views.py seems difficult, any help will be really be appreciated, here's some of my code i think will be helpful models.py class Second(models.Model): title=models.CharField(max_length=800) body=models.TextField() bodymain=models.TextField() image = models.ImageField(upload_to='profile_image/%Y/%m/%d', blank=True) date = models.DateTimeField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField('%Y/%m/%d',auto_now=True) author = models.CharField(max_length=800) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Second, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=200) body = models.TextField() created = models.DateTimeField(auto_now_add=True) approved = models.BooleanField (default=False) def __str__(self): return self.name forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'body') views.py class ListDashboardView(ListView): model = Second template_name = 'home/first_list.html' context_object_name='seconds' paginate_by='5' def get_queryset(self): context=Second.objects.order_by('-date') return context def get_context_data(self, **kwargs): ctx = super(ListDashboardView, self).get_context_data(**kwargs) ctx['object_list'] = First.objects.all().order_by('-date') return ctx class SecondDetail(DetailView): model=Second template_name = 'home/seconddetail.html' -
Get 10 random elements in Django template
I'm trying to make a quiz in Django, and I need to get ten random elements from the class Question in a template. This ten elements will be then used in a for loop inside that same template to show on screen the ten random questions to the user. Any ideas on how to select a certain number of random objects in a Django template? Thank you in advance! -
django extend templates which doesn't have any block sections
I have to extend redoc.html from drf-yasg and add a simple nav menu. when i check redoc.html in drf_yasg/templates/drf-yasg/redoc.html i find no {{block}} section. how do i extend this ? I dont want to copy the whole code and then modify. Is there any other way. {% load static %} <!DOCTYPE html> <html> <head> <title>{{ title }}</title> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{% static 'drf-yasg/style.css' %}"/> </head> <body> <script id="redoc-settings" type="application/json">{{ redoc_settings | safe }}</script> <script src="{% static 'drf-yasg/insQ.min.js' %}"></script> <script src="{% static 'drf-yasg/redoc-init.js' %}"> </script> <script src="{% static 'drf-yasg/redoc/redoc.min.js' %}"></script> </body> </html> How do i extend this? All i want is { extend 'drf_yash/redoc.html' } <body> <nav> ... </nav> <!-- Contents of above --> </body> -
Getting user's votes from query
I have a poll app with three models: class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(max_length=200) total_votes = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=120) class Voting(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) choice = models.ForeignKey(Choice, on_delete=models.CASCADE) answered_at = models.DateTimeField(auto_now_add=True) The Question model is where all questions are stored, the Choice model is where all choices to those questions are stored, and the Voting model is where user votes are stored and which choice they chose. I need to make a query where I check if the logged in user answered the question and if they did which choice they picked. How do I make this query? -
I followed the vr viewer code lab but can't make it work. Any ideas?
https://codelabs.developers.google.com/codelabs/vr_view_101/index.html#0 There is another similar thread but it wasn't answered. That's why I'm posting this question. Google VR View - Hosting code not working Also, any ideas on how to use this inside a Django App? -
Reverse for '' not found. '' is not a valid view function or pattern name - DJANGO
I have this error: NoReverseMatch at / Reverse for 'peliculas' not found. 'peliculas' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.1.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'peliculas' not found. 'peliculas' is not a valid view function or pattern name. Exception Location: C:\Users\Angel\AppData\Local\Programs\Python\Python37\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 622 Python Executable: C:\Users\Angel\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.1 Python Path: ['C:\Users\Angel\Desktop\Trabajos\Videoclub\videoclub_django', 'C:\Users\Angel\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\Angel\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\Angel\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\Angel\AppData\Local\Programs\Python\Python37', 'C:\Users\Angel\AppData\Local\Programs\Python\Python37\lib\site-packages'] I just dont get what's happening You can see full code here: https://github.com/AngelQuesada/videoclub_django Thanks in advance guys! EDITED: Do i need to add something more to the post or it's ok with the git repository? it is a small project. -
Fetching data with filters in django ORM
I have Sport object which has many Source objects which in turn has many Feed objects. Each Feed object has a published time. class Sport(Base): name = models.CharField(max_length=255, unique=True) class Source(Base): name = models.CharField(db_index=True, max_length=255) class Feed(Base): title = models.CharField(db_index=True, max_length=255) link = models.CharField(db_index=True, max_length=255, unique=True) summary = models.TextField() published = models.DateTimeField() If I want to get all Feeds in the reverse chronology of published time where source has sport A, 20 at a time. I'm not sure how to do this with django ORM. Can someone help me with this query. -
Can I record search history (by users) in Django?
I'm using MySQL as my database. I am making an application that allows employees to search a database to find the location of the item/ company asset they are looking for in a store room. Employees are required to sign into the web app and are presented with a search page. I would like to record searches for each employee in my database. Is this possible? My current views.py file def search_results(request): query = request.GET.get('q') results = box.objects.filter(Q(box_contents__icontains=query)) return render(request, 'main_app/search_results.html', {"results":results}) If it helps, I have installed django-simple-history to keep track of changes to my box contents by employees. -
What is the correct way to return images from django rest api?
Im creating a Vue single page aplication with DRF backend. I have images stored in filesystem and one of my models has a field containing the adress of the image. How can i pass the image to the frontend?