Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migration - IntegrityError: null value in column "id" violates not-null constraint
This one has a slightly different flavor from the previous versions of the same question I've seen so far. In essence, the issue is in the django_migration table itself, when the migration object is being created. DETAIL: Failing row contains (null, orders, 0036_foo_migration, 2019-07-02 20:12:51.903881+00). The suggested solutions tend towards the "nuke-em-all" approach: Getting Null Value vilates integrity error when registering user or trying to migrate However, this is not an option for me as the database has been in production for quite some time, has many records, and cannot experience severe downtime. I cannot figure out why NULL is being recorded as the ID of the Django migration object - I've also tried resetting the auto-increment counter, but to no avail. Has anyone else seen this issue? -
How to use Django-jet with Django-oscar
I am trying to integrate Django-jet with Django-oscar, but keep getting the error django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: dashboard I have tried removing oscar core dashboard app from the installed apps list using OSCAR_HIDDEN_FEATURES but does not seem to work. -
Why does pip consistently fail to install pytest-django? .dist-info directory not found error
I have a docker container setup that keeps failing to install this pytest-django==3.4.8 from requirements.txt. If I comment it out everything else installs correctly. Tried everything from tearing down the setup and rebuilding to upgrading pip to deleting the pip cache and still nothing. Any help is appreciated! Exception: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 335, in run prefix=options.prefix_path, File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 732, in install **kwargs File "/usr/lib/python2.7/dist-packages/pip/req/req_install.py", line 837, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/usr/lib/python2.7/dist-packages/pip/req/req_install.py", line 1039, in move_wheel_files isolated=self.isolated, File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 346, in move_wheel_files assert info_dir, "%s .dist-info directory not found" % req AssertionError: pytest>=3.6 .dist-info directory not found -
Django open an external link passing POST data
In my Django project i need to call from my function into my views.py an external page passing in POST format some data. i do this: in urls.py: ... url(r'^gocard/(?P<lic_num>\w+)/$', go_ccredit), ... in my views.py i create the function go_ccredit: def go_ccredit(request, lic_num=None, **kwargs): requests.post('https://www.example.com/form_test', data={'lid':lic_num,}) but i got an error because no HTTPResponse vas returned, and no page was open. I need to open an external page because i need to populate some form field with my data (using POST) and some other have to be populated by user. How can i open from my django function my external page passing data in POST ? So many thanks in advance -
How to stop logging sending message of length in django/python
In my settings.py Django project I have my LOGGING dict as LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'loggers': { '': { 'handlers': ['sentry'], 'level': 'DEBUG', 'propagate': False, }, }, 'handlers': { 'sentry': { 'level': 'DEBUG', 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler' } } } Now my problem is as soon as I execute logging.debug("hello") It prints a message in my console that is b'Sending message of length 781 to https://sentry.io/api/12345/store/' It succesfully logs to sentr but how can I get rid of this message printing in my console? -
How to load images on Heroku (Django deployed app)
I've just recently deployed my Django application using heroku, and have an issue where the profile pictures in my blog website don't save (ends up being an image that never loads). Is there any way I can solve this (and if so, without using Amazon S3)? I want to avoid Amazon S3 if possible. Is there anyway or alternatives to implement images into my Heroku website? -
How do I debug individual Django tests in vscode?
I added a launch configuration that allows me to run all tests in dajnge and another that allows me to run the server, both of these work fine. I am looking for a way to debug an individual file, but using ${file} in the arguments gives a normal path which django doesn't like. I want a way to change ${file} into a python path, so that I can debug my tests on a single file. `python manage.py test --noinput --keepdb' python.path.to.my.file' works in the command line. The following configuration seems to be almost right: { "name": "Test File", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "test", "--noinput", "--keepdb", "${file}" ], "django": true }, However, when I run this configuration I get an error, which I think is because ${file} turns into path/to/my/file instead of path.to.my.file. -
Dynamically extending django models using a metaclass
The Problem I am trying to build a framework that automatically extends model classes with additional fields. Here is a short summary of what I am trying to do: Given a model class class Pizza(models.Model): name = models.CharField(max_length=10) price = models.DecimalField(max_digits=10, decimal_places=2) I automatically want to generate a class with two additional fields per class field yielding a class similar to the following: class PizzaGenerated(models.Model): name = models.CharField(max_length=10) name_new = models.CharField(max_length=10) price = models.DecimalField(max_digits=10, decimal_places=2) price_new = models.DecimalField(max_digits=10, decimal_places=2) as you can see, for each of Pizza's properties, an additional field with the _new suffix has been added. I need my solution to work irregardless of the Model's structure. In particular, I am looking for a way that allows the replication of ForeignKey-Fields My Approach The above example of extending the Pizza class is solvable with the following code: class ResMetaclass(models.base.ModelBase): def __new__(cls, name, bases, attrs): fields = { k: v for k, v in attrs.items() if not k.startswith('_') and isinstance(v, models.Field) } attrs_extended = { **attrs, **{fieldname + '_new': fieldtype.clone() for fieldname, fieldtype in fields.items()} } bases = (models.Model,) clsobj = super().__new__(cls, name, bases, attrs_extended) return clsobj class EntityBase(models.Model, metaclass=ResMetaclass): class Meta: abstract = True … -
Django many-to-many field filter select able options
I have a many-to-many field at this I want to filter the options displayed in the form. How can I do that? I found this here Django - filtering on foreign key properties but I don't know how to pass my object to the form. The view is an UpdateView. -
how to make "set or get cookies" in Django from js code so that when you switch to another page, the radio does not stop?
` MRP.insert({ 'url': 'http://s7.voscast.com:10196/armnews', 'lang': 'hy', 'codec': 'mp3', 'volume': 65, 'autoplay': true, 'forceHTML5': true, 'jsevents': true, 'buffering': 0, 'title': 'ArmNews 106.9', 'welcome': 'Բարլուս ազիզ', 'wmode': 'transparent', 'skin': 'faredirfare', 'width': 270, 'height': 52 );` -
name 'self' is not defined when running "Tutorial.objects.all()" in cmd
I am trying to do the webapp project using django here's the code in the model.py from django.db import models class Tutorial(models.Model): tutorial_title = models.CharField(max_length=200) tutorial_content = models.TextField() tutorial_published = models.DateTimeField('date published') def __str__(self): return self.tutorial_title When running Tutorial.objects.all() in the cmd, it return errors "name self is not defined" -
django channels cannot authenticate user using django inbuilt authentication system as mentioned in documents
I want to run a consumer which requires authenticated user in my channels application channels disconnecting the consumer saying that user isn't authenticated but the user is authenticated and his cookies are updated in the browser I have followed channels documentation which authenticates user class LikeConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.user = self.scope["user"] # user = self.scope['user'] user=self.user print(user) if user.is_anonymous: await self.close() print("user is anonymous") else: await self.accept() # user_group = await self._get_user_group(self.scope['user']) await self.channel_layer.group_add("{}".format(user.id), self.channel_name) print(f"Add {self.channel_name} channel to post's group") print('connected') # @database_sync_to_async # def _get_user_group(self, user): # if not user.is_authenticated: # raise Exception('User is not authenticated.') # else: # print("user is not authenticated") # return user async def disconnect(self,close_code): user = self.scope['user'] await self.channel_layer.group_discard("{}".format(user.id), self.channel_name) print(f"Remove {self.channel_name} channel from post's group") i'm not sure what exactly the mistake is user is anonymous WebSocket DISCONNECT /like/ [127.0.0.1:50710] -
Plot audio from microphone in Django
I want to record 5 seconds of audio periodically and then send it as a blob via ajax to the server, and finally plot the audio waveform. I'm using the function below to record and send the audio to the server: function start_microphone(){ var options = {mimeType: 'audio/webm'}; const recorder = new MediaRecorder(audioStream, options); const chunks = []; recorder.ondataavailable = function(e) { chunks.push(e.data); } recorder.onstop = function(e) { var data = new FormData(); data.append('file', new Blob(chunks)); $.ajax({ url : 'ajax/analyze_audio/', type: 'POST', data: data, contentType: false, processData: false, success: function(data) { console.log("boa!"); }, error: function() { console.log("not so boa!"); } }); setTimeout(start_microphone, 0); } setTimeout(()=> recorder.stop(), 5000); // we'll have a 5s media file recorder.start(); } Then, with python, I try to read it and plot it: def analyze_audio(request): audio = request.FILES['file'] readaudio = audio.read() path = default_storage.save('somename.webm', ContentFile(readaudio)) data = np.fromfile(path, dtype=np.int16) os.remove(path) save(data, "foo.png") return JsonResponse({}) def save(data, name): if os.path.exists(name): os.remove(name) fig = plt.figure(frameon=False, figsize=(100, 128), dpi=1) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() ax.margins(0) fig.add_axes(ax) ax.plot(data, "k") fig.canvas.draw() plt.savefig(name) I do save the audio to a file "somename.webm" just to check by myself that the audio is well received and it does sound as it … -
Dynamically create model from form builder in django
I have to create model from form builder. Form field as column and title as model. is possible to implement this concept in Django? Create dynamically model from selected field of form builder and that model register in admin. i.g. I have a saree as product and that contain attribute color, prize, size and then add mobile as another product that contain attribute color, prize, ram, screen_size etc. here, color and prize common field and remaining attribute different so, create two different model in django -
How to display post and related comments on single page?
I am unable to design a code to render one particular post and it's related comments. The issue is maybe in views.py or the url. I have looked at multiple sources without any results. I am a novice to coding and feel like I am missing some essential point. Posts and comments are getting created correctly and all comments get the correct post_id assigned. My models.py is set up like this: class Post(models.Model): title = models.CharField(max_length=1000) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog-home') class Comment(models.Model): cid = models.AutoField(primary_key=True) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) comment = models.TextField() comment_date = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): super(Comment, self).save(*args, **kwargs) def __str__(self): return self.comment def get_absolute_url(self): return reverse('blog-home') class PostComment(models.Model): posts = models.ForeignKey(Post, on_delete=models.CASCADE) comments = models.ForeignKey(Comment, on_delete=models.CASCADE) My views.py is set up like this: class PostCommentView(DetailView): model = PostComment template_name = 'blog/post_detail.html' context_object_name = 'comments' ordering = ['-comment_date'] paginate_by = 7 def get_queryset(self): commentor = get_object_or_404(Comment, post_id=self.kwargs.get('post_id')) return Post.objects.filter(post_id=commentor).order_by('-comment_date') and the template for the detail view is as below: {% extends "blog/base.html" %} {% block content%} <article class="media content-section"> <img class="rounded-circle article-img" src="{{object.author.profile.image.url}}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" … -
take approved replies in comments
i took approved/published comments. However, all approved or unconfirmed replies appear. i tried this method first comment_replies=Comment.replies.objects.filter(post=post,reply=None,statusc=2).order_by('-date') However it doesn't work (sorry my misspellings) i think this problem is in this code= {% for reply in comment.replies.all %} views.py def post_detail(request,slug): post=get_object_or_404(Post,slug=slug) comments=Comment.objects.filter(post=post,reply=None,statusc=2).order_by('-date') comment_count=len(Comment.objects.filter(post=post, statusc=2)) if request.method=='POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): name=request.POST.get('name') email=request.POST.get('email') comment=request.POST.get('comment') reply_id=request.POST.get('id_comment') comment_qs=None if reply_id: comment_qs=Comment.objects.get(id=reply_id) comment=Comment.objects.create(post=post,name=name,email=email,comment=comment,reply=comment_qs,statusc=1) comment.save() messages.success(request, "Yorumunuz Onaylandıktan sonra yayınlanacaktır") return HttpResponseRedirect(post.get_absolute_url()) else: comment_form=CommentForm() context={ 'post':post, 'comments':comments, 'comment_form':comment_form, 'comment_count':comment_count, } return render(request,'post/post.html',context) models.py class Comment(models.Model): STATUS_C_DRAFT = 1 STATUS_C_PUBLISHED = 2 STATUSES_C = ( (STATUS_C_DRAFT, 'Draft'), (STATUS_C_PUBLISHED, 'Published'), ) post=models.ForeignKey(Post,verbose_name='post',related_name='comment',on_delete=models.CASCADE) name=models.CharField(verbose_name="name",max_length=60,blank=False) email=models.EmailField(max_length=120,blank=False,verbose_name="email") comment=models.TextField(max_length=1000,verbose_name="comment") reply=models.ForeignKey('Comment',null=True,related_name='replies',on_delete=models.CASCADE) date=models.DateTimeField(auto_now_add=True) statusc = models.SmallIntegerField(choices=STATUSES_C,default=STATUS_C_DRAFT) class Meta: verbose_name="Yorum" verbose_name_plural="Yorumlar" def __str__(self): return 'Üst Yorum: %s' % (self.comment) html file comments; {% for comment in comments %} <!-- POST COMMENT --> <div class="post-comment"> <!-- POST COMMENT USERNAME --> <p class="post-comment-username">{{ comment.name }}</p> <!-- /POST COMMENT USERNAME --> <!-- POST COMMENT TIMESTAMP --> <p class="post-comment-timestamp">{{ comment.date |timesince }} Önce</p> <!-- /POST COMMENT TIMESTAMP -->... html file comments reply {% for reply in comment.replies.all %} <div class="post-comment"> <!-- POST COMMENT USERNAME --> <p class="post-comment-username">{{ reply.name }}</p> <!-- /POST COMMENT USERNAME --> <!-- POST COMMENT TIMESTAMP --> <p class="post-comment-timestamp">{{ reply.date|timesince }} Önce</p> … -
How to connect microsoft azure dataware house server with django?
Trying to connect to a datawarehouse. This is the configuration I am using DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'dbname', 'USER': 'username', 'PASSWORD': 'pass', 'HOST': 'xyz.database.windows.net', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } When I am trying to run the migrate command its giving me the error that Enforced unique constraints are not supported in Azure Data Warehouse. To create an unenforced unique constraint you must include the NOT ENFORCED syntax as part of your syntax. -
Django Rest Framework: Can't get over strange error
Trying a simple request: urls.py from django.conf.urls import url from django.urls import include, path from rest_framework import routers from django.http import HttpResponse from rest_framework.urlpatterns import format_suffix_patterns from .public_views import NavigationBar router = routers.DefaultRouter() router.register(r'navbar', NavigationBar, basename="NavigationBar") urlpatterns = [ path('', include(router.urls)) ] urlpatterns = format_suffix_patterns(urlpatterns) public_views.py from django.shortcuts import render from rest_framework.views import APIView from rest_framework.permissions import AllowAny from rest_framework.throttling import UserRateThrottle from rest_framework.decorators import api_view, throttle_classes from . view_utils import * class OncePerDayUserThrottle(UserRateThrottle): rate = '1/day' class NavigationBar(APIView): """ obtain up to date navigation bar (or side menu navigation) hierarchy. """ permission_classes = ([AllowAny]) def get(self, request, format=None): """ get user addresses """ return Response("this is a good response") def get_extra_actions(cls): return [] When I API call the /v1/navbar or /v1/navbar/ endpoints (I do have my main urls.py lead all /v1/ traffic to another dedicated urls.py), I am getting the following error: AttributeError at /v1/navbar type object 'NavigationBar' has no attribute 'get_extra_actions' Request Method: GET Request URL: http://web/v1/navbar Django Version: 2.1 Exception Type: AttributeError Exception Value: type object 'NavigationBar' has no attribute 'get_extra_actions' Exception Location: /usr/local/lib/python3.6/site-packages/rest_framework/routers.py in get_routes, line 200 Python Executable: /usr/local/bin/uwsgi Python Version: 3.6.8 Python Path: ['.', '', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages'] Server time: Tue, 2 Jul … -
How to write a data migration to rename objects in the production database?
I changed the instances of "Discipline Points" to "Accountability Points" in the code but I am unable to rename these objects in the database. In a few spots, I have code that grabs a template named "Accountability Points" but this will fail to find an object matching that query because the name of these objects are not changed in the database. An example of code that grabs this is template = NotificationTemplate.objects.get(name="Accountability Points"). Currently, I'm attempting to write a data migration to rename these objects but I'm kind of unsure exactly how to accomplish this. I haven't found much on how to do this specifically, but I've looked at the RenameField migrations operation and I think the solution to my problem could be something similar. I have also tried grabbing all of the objects with the name "Discipline Points" and think a For loop would work to grab each object and rename it. # Generated by Django 1.11.6 on 2019-05-09 21:05 from __future__ import unicode_literals from django.db import migrations def change_to_accountability(apps, schema_editor): notification = apps.get_model('hr', 'NotificationTemplate') discipline = notification.objects.get(name="Discipline Points") for disc in discipline: disc.new_name = "Accountability Points" disc.save() class Migration(migrations.Migration): dependencies = [ ('hr', '0012_auto_20190509_1705'), ] operations = [ … -
Snippets aren't displayed in the wagtail admin page
I have a snippet called event, After upgrading to wagtail 2.5.1 (Still i am not sure if this issue is related to version 2.5.1) The previous events aren't displayed on the wagtail admin page anymore. However i am able to search for them in the search box.any help is appreciated -
How to change Text field to Buttons
Can any body tell me the best practice or way to change Text field to the Button with value 0 or 1. Let me clear what I want so i have here(see below) django form with the 2 field called Up_vote and Down_vote and when I submit it stores pretty nicely into the Votes table. But what I what is to have two buttons like stacoverflow have for up_vote and down_vote and when someone press on the up_vote it should submit value 1 automatically to the database and when someone press the down_Vote it sould submit the value 0 to the database table. see like this: so basically how i can convert text fields to the two buttons, I dont now how i can do with the javascript or with other method. -
Problems using wildwebmidi midi player
I'm trying to add this github code to my project: https://github.com/yazgoo/wild-web-midi It works perfectly when I try it local, but when I try it in my webpage, based on Django, it throws me the following error: uncaught exception: could not load memory initializer wildwebmidi.js.mem I try to load all the scripts from my static folder. Does anybody know how to manage this problem? I'm not sure if it is because of the URLs or something like that. -
How to export django model to pandas dataframe sorted by specific column
I'm working on a django web app which visualizes data stored in a SQLite in the browser using bokeh. Since I want to display the data as a stacked area plot I concluded it might be helpful to use the pandas library to save the data from my django model to a dataframe before plotting. My Django models.py includes the following model: class Activity(models.Model): def __str__(self): return self.title title = models.CharField(max_length=50) sport = models.ForeignKey(Sport, on_delete=models.CASCADE) date = models.DateField(blank=False) duration = models.FloatField() distance = models.FloatField(blank=True, null=True) description = models.CharField(max_length=50, blank=True, null=True) trace_file = models.ForeignKey(TraceFiles, on_delete=models.CASCADE, blank=True, null=True) Some example data in the SQLite db could look similar to: | id | title | date | duration | sport_id | trace_file_id | description | distance | |--------------------------------------------------------------------------------------------| | 1 | biking01 | 2019-01-01 | 183 | 1 | 16 | NULL | 142 | | 2 | running17 | 2019-01-01 | 45 | 2 | 2 | NULL | 14 | | 3 | biking02 | 2019-01-01 | 67 | 1 | 18 | NULL | 45 | What would be the best way to read from the model and convert the data to a pandas dataframe? For example I have similar … -
Import error while trying to import a variable within a function in another python script
I have created a function in views.py which is def func(request).Basically, I tried using the variable var, in another python file, say z.py, by typing: from views import func but I got the error ImportError: cannot import name func. Please help me out. I want to use the variable var in the other python script, but am getting this error. -
Auto-Scheduling Django Celery Tasks
I have a django project that checks and backs up a large amount of data from user's accounts they've authorized. Is there a smart way to distribute the scheduling, say if I want to do it twice a day as to not overload my celery server?