Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django JSONResponse is returning a string and not JSON
I am using a Django view to return a JSON object. However when I use the method below, I get a string representation of the dictionary and not a JSON object. def api_dataset_index(request): upload_file = request.FILES.get('file') if upload_file: config_str = upload_file.read().decode("utf-8") d = Dataset.from_yaml(config_str) return JsonResponse(model_to_dict(d)) Response - "{\"id\": 31, \"name\": \"effort\", \"description\": \"Expressions of customer effort or ease.\", \"multilabeled\": false}" Am I doing something wrong here? or is JSONResponse supposed to return a string? -
Unable to install/run rpy2 in Django
I am having multiple issues in Installing rpy2 in Django. When i write pip install rpy2 it gives me Visual studio installation errors, I have fulfilled all the requirements of visual related errors but still it remain unsolved I have mentioned it asked here before When I install rpy2 using wheel(.whl) file it gets installed but when I run my rpy2 code it gives Cstack limit error here Is there any fix which can solve my long lasting problem?? -
(Django) Limited ForeignKey choices by Current User in UpdateView
I recently was able to figure out how to do this in the CreateView, but the same is not working for the UpdateView (Here's the original post on how to do it in the CreateView: (Django) Limited ForeignKey choices by Current User) Essentially, I need it to display only the Universes created by the currently logged in user, but by default, it displays all universes. When I try to set a form_class and have it mimic the solution for CreatView, it spits out an improperly configured error. models.py: class Universe(models.Model): user = models.ForeignKey(User,related_name='universe',on_delete=models.CASCADE) name = models.CharField(max_length=100, unique=True) description = models.TextField(max_length=2000,blank=True,default="") def __str__(self): return self.name def get_absolute_url(self): return reverse('universe:singleuniverse',kwargs={'pk': self.pk}) class Meta: ordering = ['name'] unique_together = ['user','name'] class Character(models.Model): user = models.ForeignKey(User,related_name='characters',on_delete=models.CASCADE) universe = models.ForeignKey("story_universe.Universe", on_delete=models.CASCADE) name = models.CharField(max_length=255,unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('character_developer:singlecharacter',kwargs={'pk': self.pk}) class Meta(): ordering = ['name'] unique_together=['user','name'] views.py: class UpdateCharacter(LoginRequiredMixin,generic.UpdateView): model = Character fields = ('universe','name') template_name = 'character_developer/character_update_form.html' -
Accessing the contents of a topic
How do I pass the id of a model that is within a model model.py class Topic(models.Model): """ A topic the user is learning about """ text = models.CharField(max_length = 200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete = models.CASCADE) def __str__(self): return self.text class Entry(models.Model): enttopic = models.ForeignKey(Topic, on_delete = models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add = True) class Meta: verbose_name_plural = 'entries' def __str__(self): return self.text class Document(models.Model): doctopic = models.ForeignKey(Entry, on_delete = models.CASCADE) docfile = models.FileField(upload_to = 'documents/', blank = True, null=True) upload_at = models.DateTimeField(auto_now_add = True) As you can see, Entry model belongs to Topic, and Document belongs to Entry. Topic>Entry>Document. Now, I know how to get the contents of Entry through Topic. views.py def topic(request, topic_id): topic = Topic.objects.get(id = topic_id) entries = topic.entry_set.order_by('-date_added') images = topic.image_set.order_by('-upload_at') context = {'topic': topic, 'entries':entries, 'images': images} return render(request, 'learning_logs/topic.html', context) But how do I get the contents of Document through Entry? I don't want a hyperlink. I wanted to be so that once someone clicks on the Topic, the Entry and Documents should be revealed at the same time. -
Bootstrap form does not show instance's data
I am trying to retrieve an instance's current data to bootstrap form for update. When i use {{user_form.as_p}} all current data is filled automatically however replace it with bootstrap forms it seems empty. Here is my python and html files: views.py def update_profile(request): if request.method == 'POST': user_form = RegisterForm(request.POST, instance=request.user) if user_form.is_valid(): user_form.save() return redirect('profile') else: user_form = RegisterForm(instance=request.user) return render(request, 'blog/update_profile.html', { 'user_form': user_form, }) update_profile.html <form method="post"> {% csrf_token %} <div class="form-group"> <label for="formGroupExampleInput">Name</label> <div id="formGroupExampleInput"> <input class="form-control" name="first_name" maxlength="150" autofocus required="" id="id_first_name" type="text" placeholder="First name" > </div> ... <div class="form-group"> <button type="submit" class="btn btn-success" id="formGroupExampleInput5">Save changes</button> </div> </form> forms.py class RegisterForm(UserCreationForm): email = forms.EmailField(max_length=200, help_text='Required') class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email', 'password1', 'password2') -
Django dynamic choicefields removed in cleaned_data despite being in POST data?
I've followed this example from Jacobian to dynamically add choice fields to a form depending on the ID of the product being viewed. The fields load fine, however, on submit they are not in the form.cleaned_data despite being added to self. Oddly the are in QueryDict in the POST object. From reading around a common cause seems to be that the form was expecting something else so dynamic labels cause issues but I can't see any difference to the example so struggling to understand where I'm going wrong. Any pointers massively appreciated. Bigger picture Ideally, the form would load the rest of the questions as soon as the first choice field is selected by the suer but have decided to just stick with loading extra questions only if an ID has been passed to reduce complexity for now. View code directAndIndirectReqs is an array of questions, this is passed to the form via the variable 'extra' which is used to generate the questions in the form by generating a self.form['new_id'] for each question. I switched to using request.method = POST in this version as the simpler version in the example didn't work either and this felt easier to follow. Theoretically, … -
Django: DeleteView pass argument from ForeignKey's Model to get_success_url
After the user deleted a PieceInstance I would like to redirect him to the Piece to which the PieceInstance belonged to. I use the default DeleteView and would like to pass the Piece id (Piece via PieceInstance referenced by ForeignKey) to the get_success_url method. self.piece.pk seems not to get the id of the corresponding Piece. models.py class PieceInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular Piece across whole system') piece = models.ForeignKey('Piece', on_delete=models.SET_NULL, null=True) ... class Piece(models.Model): title = models.CharField(max_length=200) ... views.py class PieceInstanceDelete(LoginRequiredMixin, DeleteView): model = PieceInstance def get_success_url(self): return reverse_lazy('piece-detail', kwargs={'pk': self.piece.pk}) urls.py path('piece/<int:pk>', views.PieceDetailView.as_view(), name='piece-detail') -
Deploy migration files to production on pythonanywhere
I have a local django project which is also hosted on pythonanywhere. I just run into a merge conflict with the migration files (which I solved). Now I a wondering; should deploy my local migration files alongside the code or have two separate set of migration files? -
Django OSError [Errno 13] Permission denied: '/home/django/media_cdn/1.png' solution
setting.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), #'/var/www/static/', ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn") MEDIA_URL = '/media/' models.py image = models.ImageField(null=True, blank=True, height_field="height_field", width_field ="width_field") The error text is written in the title. It is telling me it doesn't have permission.Please help... -
Django toolbar: not showing the results for query with filter with greater than
I have a simple query in Django. I have Django toolbar installed to check the sql queiries and the corresponding data I have the below django query with filter. RecipePosition.objects.all().filter(mass_quantity__gt = 0) Django gets all the objects whose mass_quantity is greater than 0. But when i check the sql in the django - toolbar. it shows: SELECT "recipes_recipeposition"."id", "recipes_recipeposition"."name", "recipes_recipeposition"."title", "recipes_recipeposition"."updated", "recipes_recipeposition"."timestamp" FROM "recipes_recipeposition" WHERE "recipes_recipeposition"."mass_quantity" > 'Decimal(''0'')' ORDER BY "recipes_recipeposition"."sequence_number" ASC I tried this command in sqlite browser also, but it didnt show any results. Why django-toolbar is not showing the correct sql. As per me the sql should be: SELECT "recipes_recipeposition"."id", "recipes_recipeposition"."name", "recipes_recipeposition"."title", "recipes_recipeposition"."updated", "recipes_recipeposition"."timestamp" FROM "recipes_recipeposition" WHERE "recipes_recipeposition"."mass_quantity" > 0 ORDER BY "recipes_recipeposition"."sequence_number" ASC and this when tested in slite browser shows the results. -
how display button for special users django
how can display button example ' download file.pdf ' for special users in django. Django version 2, 1, 0 Python version 3.7.0 -
Django Rest Framework - call serializer.to_internal_value on a null value
I am attempting to write a Field Serializer for my django API that passes null to a custom .to_internal_value method. My use case is for two datetime fields that make up a time range. I want a user of my API to be able to give me something along the lines of "start_dt": null in a PUT/POST/PATCH request and have my serializer translate that into datetime.datetime.min (or, in the case of end_dt, datetime.datetime.max). Here is what I have so far. I am able to get Object->JSON serialization to work well (translates datetime.min and datetime.max values to None) using the .to_representation(self, value) method - however it does not seem to call .to_internal_value(self, value) when converting from null->None - and instead passes None through to the rest of my logic whenever one of the two fields is given as null. class CustomDateTimeField(serializers.Field): def __init__(self, *args, **kwargs): self.datetime_field = fields.DateTimeField() self.infinity_direction = kwargs.pop('infinity_direction', None) if not (self.infinity_direction == '+' or self.infinity_direction == '-'): raise AssertionError("Expected CustomDateTimeField to be created with `infinity_direction` equal to either '+' or '-'") super().__init__(*args, **kwargs) def to_representation(self, value): """ Represent both MAX and MIN times as None/'null' Else return a normal datetime string """ if value == min_dt or … -
(Django) Limited ForeignKey choices by Current User
I have a feeling I'm missing something small here but I've been working on it for a while and can't figure it out. I have an app called story universe where the user creates one with a name and description. I then have a character creator class where the user can create a character within that universe. This all works fine, except when the user goes to create their character they see a list of all universes created by all users. Then there are other apps that will also mimic what I'm trying to do with the character creator. I need to limit the Story Universes to only those created by the currently logged in user. I've tried a few different ways and had the most success with the following, but with this code, no Universe appears when trying to create a new character. Universe models.py class Universe(models.Model): user = models.ForeignKey(User,related_name='universe',on_delete=models.CASCADE) name = models.CharField(max_length=100, unique=True) description = models.TextField(max_length=2000,blank=True,default="") def __str__(self): return self.name def get_absolute_url(self): return reverse('universe:singleuniverse',kwargs={'pk': self.pk}) class Meta: ordering = ['name'] unique_together = ['user','name'] Character models.py class Character(models.Model): user = models.ForeignKey(User,related_name='characters',on_delete=models.CASCADE) universe = models.ForeignKey("story_universe.Universe", on_delete=models.CASCADE) name = models.CharField(max_length=255,unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('character_developer:singlecharacter',kwargs={'pk': self.pk}) class Meta(): … -
Django : Filter on the basis of dictionary values
I have my django admin as - User Name City Number John_Lincoln_roma_1.0 John_Lincoln_roma roma 1.0 Eddie_paul_roma_1.1 Eddie_paul_roma roma 1.1 Shin_roma_1.2 Shin_roma roma 1.2 Sinclair_madrid_1.0 Sinclair_madrid madrid 1.0 Jessie_madrid_1.1 Jessie_madrid madrid 1.1 I want to apply query which should return me the User on the basis of Max number which is 1.2 & 1.1 and the record it should give me are Shin_roma_1.2 and Jessie_madrid_1.1 Below is the snippet which I tried - some_object.values('name').annotate(number=Max('number')).order_by() Getting the result as - result = [{'number': u'1.2', 'name': u'Shin_roma'}, {'number': u'1.1', 'name': u'Jessie_madrid'}, print type(result) <class 'django.db.models.query.QuerySet'> I want a query or filter that returns the User based on filtering the dictionary values which is in result I tried something like this which I didn't get the result (I know this is wrong) - result.filter(result__number="number",result__city="city") Gone through the stackoverflow but didn't get the solution. Please let me know if anything is unclear. I hope the above is clear. Thanks.! -
How to embed an image in an email as inline image in django using base64 data of image
I am trying to send an email from django views which contains an image embeded inline. I don't want to expose the image in some server so I am trying to use base64 encoded format to embed image. Below is the code I have written so far: get image date in Base64 format def get_image(f_path): with open(f_path, 'rb') as f: img_data = f.read() img = 'data:image/png;base64{}'.format(base64.b64encode(img_data).decode()) return img Function to send email def send_email(to_emails): img_data = get_image("/myfolder/abcd.png") template = "<h1> WTH </h1> <br/> <img src=\"%s\" />" %(img_data) message = EmailMultiAlternatives( subject="Just a subject don't bother", body="blah blah", from_email="xxxx", to=[to_emails], ) message.attach_alternative(template, "text/html") message.send(fail_silently=False) Email is sent but without the image. Please tell me if I am missing something. Thanks in advance. -
Finding source of Image for PDF
so I am trying to figure out how I can change the image of this pdf template that was created for me on my Django App. I tried to change the img src to a direct link of the picture that I would like but the result turned out to be the same picture. What might be the best way to change the image? I have tried many different ways to changing the img src myself but its not budging. -
Django - Url patatterns dose not work
I started working with Django yesterday and I have a little error. I searched on the internet but I cant find the answer for my problem. I made the main app and then I make a little app and tried to link it to the main. Here is my code urls.py from django.contrib import admin from django.urls import path, include ulrpatterns = [ path('admin/', admin.site.urls), path('^$', include('personal.urls')); ] in my personal.urls I have from django.urls import path, include from . import views ulrpatterns = [ path('^$', views.index, name="index"); ] and in views.index I have def index(request): return render(request, 'personal/home.html') Any help would be awesome, thank you!!! -
Django: access form argument in CreateView to pass to get_success_url
I use CreateView to let a user create a Piece. The Piece will automatically be assigned an id. After the user created the Piece I would like to redirect using get_success_url to another CreateView to add Versions of the Piece. First of all, I do not know where the id of the Piece comes from (since it is generated automatically; I imagine this is the row number of the Piece in the model). How can I access this id to pass it to get_success_url? The get_context_data method in CreateView seems not to be able to get the Piece id. views.py class PieceCreate(LoginRequiredMixin, CreateView): model = Piece fields = ['title', 'summary', 'created', 'piece_type'] initial = {'created': datetime.date.today()} def form_valid(self, form): form.instance.creator = Creator.objects.get(user=self.request.user) return super(PieceCreate, self).form_valid(form) def get_context_data(self, **kwargs): context = super(PieceCreate, self).get_context_data(**kwargs) return context['id'] def get_success_url(self): return reverse_lazy('pieceinstance-create', kwargs={'pk': self.get_context_data()}) urls.py path('pieceinstance/create/<int:pk>', views.PieceInstanceCreate.as_view(), name='pieceinstance-create') -
Incorrect work of pagination after adding a filter
Before adding a filter, pagination worked without problems. Added a filter based on django-filters, and now only the first page gives the right context, starting from the second page - a full list of instances is displayed. I think the problem is in the reques.GET contained in the template to get the filtered values. It turns out that both the filter and the pagination use the GET method, when switching to the second page of the pagination, the if request.GET condition for the filter is triggered, and since the filter contains no restrictions, a complete list of elements from all pages is output. Maybe I'm wrong and the reason is different. Help me understand how to make pagination and filtering. When go to any page of pagination, the output of the pagination disappears. This behavior corresponds to the display of objects when filtering. Because Initially, I did not set the task to add pagination to the results of the filter, and apply it only to the full unfiltered list. templates.html {% block content %} <!-- Page Content --> <div class="container"> <!-- Filter --> <header class="custom-top"> <form method="get"> ### filters form <div class="well"> <div class="row"> <div class="form-group col-sm-4 col-md-3 "> <b>{{ … -
integer out of range error for models django
When making a new post, he gives error. code in my models: class Post(models.Model): STATUS_CHOICES = ( ('draft','Draft'), ('published','Published'), ) uuid = models.UUIDField(primary_key = True, default = uuid.uuid4) title =models.CharField(max_length = 60,null = False, help_text = 'Enter a Title') slug = models.SlugField(max_length = 60,null = False, help_text = 'Enter a Slug') authors = models.ManyToManyField(User, help_text = 'Selection a Author') summary = models.TextField(max_length = 1000, null = True, blank = True, help_text = 'Write Summary Text') description = RichTextField(blank= True, null= True, verbose_name = 'message', help_text = 'Write Full Text') published_at = models.DateTimeField(default = timezone.now, help_text = 'Select The Time To Register') created = models.DateTimeField(auto_now_add = True,) updated = models.DateTimeField(auto_now = True,) status = models.CharField(max_length = 60, choices = STATUS_CHOICES, default = 'draft', help_text = 'Selection draft or publish') tags = TaggableManager(help_text = 'Write tags') category = models.ManyToManyField(Category) class Meta: verbose_name_plural = 'Post' def __str__(self): return "Post object (uuid = {} & title = {})".format(self.uuid,self.title) def display_category(self): return ', '.join([category.name for category in self.category.all()]) display_category.short_description = 'Category' and my error is: File "C:\Users\Mr-py-dj\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) django.db.utils.DataError: integer out of range -
How to dump (and reload) django allauth social apps data to/from file
I am using django 2.0.8,Python 3.5 and django-allauth. I have manually created the social app data using the Home › Social Accounts › Social applications menu in the django admin page. However, I want to automate this process (to eliminate manually creating the social apps via the django admin), as I will be deploying the website via Docker, on a virtual machine. I know python manage.py dumpdata allows one to dump data from a django project, but it is not clear how to dump only the data relevant for django-allauth - namely: site information (sites app) allauth social applications how do I use python manage.py dumpdata/load to dump/load this data? -
Get RecursionError / KeyError trying to add Periodic Task in Celery beat
I try to setup some periodic tasks with Celery beat on Django. I'm using next setup: python3.6 django==1.11.10 celery==4.2.1 kombu==4.2.1 My schedule worker runs in Docker container via docker-compose and starts with next command: celery -A proj beat --loglevel=debug -s /src/celerybeat-schedule Without periodic tasks added everything is ok and I get these lines in console: [2018-08-28 17:06:05,261: DEBUG/MainProcess] Setting default socket timeout to 30 [2018-08-28 17:06:05,267: INFO/MainProcess] beat: Starting... [2018-08-28 17:06:05,298: DEBUG/MainProcess] Current schedule: [2018-08-28 17:06:05,298: DEBUG/MainProcess] beat: Ticking with max interval->5.00 minutes [2018-08-28 17:06:05,299: DEBUG/MainProcess] beat: Waking up in 5.00 minutes. But when I try to add periodic task (right after Celery setup): @app.on_after_configure.connect def setup_periodic_tasks(sender): sender.add_periodic_task(10.0, test.s('hello'), name='add every 10') @app.task() def test(arg): print(arg) I get KeyError with this lines: [2018-08-28 17:11:56,666: WARNING/MainProcess] Traceback (most recent call last): [2018-08-28 17:11:56,666: WARNING/MainProcess] File "/usr/local/lib/python3.6/site-packages/kombu/utils/objects.py", line 42, in __get__ [2018-08-28 17:11:56,666: WARNING/MainProcess] return obj.__dict__[self.__name__] [2018-08-28 17:11:56,666: WARNING/MainProcess] KeyError [2018-08-28 17:11:56,666: WARNING/MainProcess] : [2018-08-28 17:11:56,667: WARNING/MainProcess] 'tz' then same errors with 'timezone' and 'data' and then A LOT OF THIS (RecursionError): [2018-08-28 17:11:57,050: WARNING/MainProcess] File "/usr/local/lib/python3.6/collections/__init__.py", line 987, in __getitem__ [2018-08-28 17:11:57,050: WARNING/MainProcess] if key in self.data: [2018-08-28 17:11:57,051: WARNING/MainProcess] File "/usr/local/lib/python3.6/site-packages/celery/utils/collections.py", line 126, in __getattr__ [2018-08-28 17:11:57,051: WARNING/MainProcess] return self[k] … -
Scrolling in Django Website not working
In my webpage made with django the scrolling is not working. I have to zoom out the page in order view the full content. help me fix it -
django add variable to string inside a html tag
I was trying to add a variable to a string inside a html tag, but it didn't work. Here is the case, I got a variable {{comment.id}}, which is a number, 41. How could I combine {{comment.id}} with "#multiCollapseExample" in the href="..." part so it becomes href="#multiCollapseExample41"? post_detail.html <a class="btn btn-primary" data-toggle="collapse" href="#multiCollapseExample41" role="button" aria-expanded="false" aria-controls="multiCollapseExample41">reply</a> Any way out? Thanks! -
Django regex path only sending first match as argument
The behavior I'm trying to get is a "handler" endpoint whereby the url pattern is split along the delimiter /, and the resulting array is passed as the *args of the view. I'm trying to accomplish this using the following urlpatterns : urlpatterns = [re_path(r'handler/([^/]+)', views.handler)] For the time being, my views.handler merely returns its *args and **kwargs for debugging purposes. What I'm seeing is that only the first match is being sent to the view as an argument. So for example GET /handler/arg1/arg2/ calls views.handler(arg1) and arg2 is simply ignored. I could easily write a pattern that merely catches anything that starts with /handler/ and parse the request within the view, but that just seems so much less elegant and leaves the interpretation of the pattern to the view, which is just bad design. Any ideas as to why only the first match is being sent to the view ? The docs seem to imply that all matches should be sent : When a match is made, captured groups from the regular expression are passed to the view – as named arguments if the groups are named, and as positional arguments otherwise.