Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to enter ForeginKey values in a model with CreateView
I am creating a wiki and need to put in values in the model called revision. This table has a foreigkey to wikipage. My problem is that I am unable to insert values in the revision model. I have tried using def form_valid(self, form) like you would when entering user, without any luck. Models.py class Wikipage(models.Model): title = models.CharField(max_length=100) date_created = models.DateTimeField('Created', auto_now_add=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Wikipages" class Revision(models.Model): wikipage = models.ForeignKey(Wikipage, null=True, on_delete=models.CASCADE, related_name='revisions') content = models.TextField('Content') author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) last_edit = models.DateTimeField('Last Edited', auto_now=True) comment = models.TextField('Comment', blank=True) class Meta: verbose_name = 'Revision' verbose_name_plural = 'Revisions' ordering = ['-last_edit'] get_latest_by = ['last_edit'] def __str__(self): return self.content View.py Class WikipageCreateView(CreateView): template_name = 'wiki/wikipageform.html' model = Wikipage fields = ['title'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) The template are as simple as possible with {{ form.as_p }} and all the necessary stuff. -
how to use django_tables2 to filtering table containing data that does not come from django model
I am a newbie in Python and django. I'm creating web application which expose some part of HTTP API of one of my company Security System. Wrapper for the API I keep in file ReducedHXAPI.py. The only data which I keep in db are ip address of the Security System, and authentication data used to login to API. I successfully created a code which shows sortable list of hosts registered in company Security System. Now I'm trying to implement exporting created list of hosts and enabling inline filter for columns. Unfortunately all my attempts (based on tutorials and docs on: https://django-tables2.readthedocs.io/en/latest/index.html and https://django-filter.readthedocs.io/en/master/ ) produce only errors. Could someone help me in making it works and understanding philosophy of django_tables2 and django_filters, please? models.py: from django.db import models class ServerConnection(models.Model): ConnectionName = models.CharField('Connection Name', max_length=200, help_text="Enter name for this connection") ServerAddress = models.CharField('Server Address', max_length=200, help_text="Enter name or IP address of FireEye HX console") APIUser = models.CharField('API User', max_length=200, help_text="Enter name of user who has access to API") APIPassword = models.CharField('API Password', max_length=200, help_text="Enter name of user who has access to API") def __str__(self): """String for representing the Model object (in Admin site etc.)""" return self.ConnectionName ============================================================ views.py (extract) import … -
Sending email from modal in Django
I'm trying to create a simple contact form in a modal window and send email to console at the beginning but it doesn't work. I've got everything set. I've got email backend set correctly as I can send an email from the console. When opening the modal, the url of the website is not changing. Does it have something to do with this? This is what I'm getting in the console [02/Jul/2019 22:30:22] "GET /contact/ HTTP/1.1" 200 1224 [02/Jul/2019 22:30:29] "POST / HTTP/1.1" 200 2229 views.py def email(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): mail = form.cleaned_data["from_email"] subject = form.cleaned_data["subject"] message = form.cleaned_data["message"] send_mail(subject, message, mail, ["example@gmail.com"], fail_silently=False) messages.success("Done") return redirect("homepage") else: form = ContactForm return render(request, "home_page/contact_form.html", {"form": form}) forms.py class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea) urls.py urlpatterns = [ path('', views.home, name='homepage'), path('contact/', views.email, name='contact')] And html {% load crispy_forms_tags %} <h1>Leave me a message</h1> <form method="post" action=""> {% csrf_token %} {{ form|crispy }} <div class="form-actions"> <button type="submit">Send</button> </div> </form> -
I created backend in Django with REST API and added these api with mobile apps but for website I am calling from another server
I created backend in Django with REST API and added these api with mobile apps but for website I am calling from another server which is built in .net framework now this server call API and then implement data with frontend. can you tell me this is good option or not because this is adding one another server means it can make my process slow and cost me more but for security purpose is it good or not? first I implemented my api direct in frontend but everyone can check my api and this can harm my website. I am creating e-commerce website. I didn't used php because I know .net better. -
Make ModelForm Field Larger in Django
I have a ModelForm where there is a description field. Django generates the field at its standard size but I'd like to make it, say, twice as large. I seem to be failing at Googling how to do this. HTML {% extends 'base.html' %} {% block body %} <div class="container"> <form method="POST"> <br> <br> <br> {% csrf_token %} <div class="column"> <label for="form.reference">Reference ID: </label><br> <!-- <input type="text" value="{{ reference_id }}">--> {{ form.reference }} <br> </div> <div class="description"> <div class="column"> <label for="form.description">Description: </label> <br> {{ form.description}} </div> </div> <div class="column"> <label for="form.cases">Cases: </label> <br> {{ form.cases }} <br> </div> <div class="column"> <label for="form.count">Count: </label> <br> {{ form.count }} <br> <br> </div> <br> <br> <button type="submit" name="add_mani" style="border-color: #7395AE;">Add Line</button> </form> Forms.py class CreateManifestForm(forms.ModelForm): class Meta: model = Manifests fields = ('reference', 'cases', 'description', 'count') Again I am looking to increase the size of the field for 'description' -
How to get form widgets to render in custom template
I am attempting to have dJango form widgets render on my HTML page. forms.py assignment: class MenuItemsFormBase(forms.Form): name = forms.CharField(max_length=200) html assignment: <div class="col-sm-6 ce_name"> <b>Name:</b><br/> {{ form.name }} </div> From what I understand, this should create an element. Instead, it is rendering the following: " Ricky " What am I doing wrong that is preventing the widgets from rendering? -
Django CBV link product to user and allow to modify only his data
hello I did not understand the principle of django CBV for example I want to create an anonymous voting system and I want to make sure for example that the user can vote only once and I want to crypt also the vote and do some manipulation on the field. add to that I would like to know how to connect an object created to the user and thus allow it to change only these objects (election) my Model #model from datetime import datetime from django.http import Http404 from django.db import models, connection from django.db.models import Q from dzstudent import settings from django.contrib.auth import get_user_model User = get_user_model() class VotingNotAllowedException(Exception): pass class Election(models.Model): """ Represents elections. which can be composed of one or more ballots. Voting only allowed between vote_start and vote_end dates. """ userElec = models.ForeignKey( User, related_name="election", on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=False, unique=True, help_text="Used to uniquely identify elections. Will be shown " + "with ' Election' appended to it on all publicly-visible pages.") introduction = models.TextField(blank=True, help_text="This is printed at the top of the voting page below " + "the header. Enter the text as HTML.") vote_start = models.DateTimeField(help_text="Start of voting") vote_end = models.DateTimeField(help_text="End of voting") def __str__(self): … -
Graphene query hangs indefinitely when testing with pytest
I am trying to test my backend, written in Django 2.2.2 and Python 3. I created some graphql queries which are definitely working when testing with the graphql web interface. When testing with pytest and the graphene test client, however, these queries would always hang indefinitely. I put together a reproducible example which is actually based on the code example from the graphene-django documentation. test_example.py: import pytest import graphene from graphene_django import DjangoObjectType from graphene.test import Client from django.db import models class UserModel(models.Model): name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class User(DjangoObjectType): class Meta: model = UserModel class Query(graphene.ObjectType): users = graphene.List(User) def resolve_users(self, info): return UserModel.objects.all() schema = graphene.Schema(query=Query) client = Client(schema) def test_user(): query = ''' query { users { name, lastName } } ''' result = client.execute(query) assert 0 # dummy assert This example behaves in the same way (stalls forever, no errors). I am using the latest graphene-django (2.3.2) and pytest (4.6.3). I should probably also mention that I'm running this inside a Docker container. Any ideas why this happens? Is this a bug in the graphene-django library? -
What jobs are available for js and Django web app development?
How useful is it in the current software engineer world to know how to make web apps with javascript frontend and Django backend? I want to make a web app from these but I also want to know if this fun project could get me a job doing the same thing at real companies. I have searched a lot on Google for answers but it just pops up with things like if JS is better than Python. -
Date Validation --> end date must be greater than start date
I need to write a script where it validates the end date is greater than the start date. Also the start date/end date cant be before the current date. Needs to be written in Django 1.8. -
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" …