Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why django don't reset UserFactory username in setUp when full test suite is run?
I have a UserFactory like this: class UserFactory(factory.django.DjangoModelFactory): class Meta: model = settings.AUTH_USER_MODEL username = factory.Sequence(lambda n: f'user_{n}') and a test class like this one: class MyClass(TestCase): def setUp(self): self.user1 = UserFactory() self.user2 = UserFactory() print(self.user1) print(self.user2) print(User.objects.all()) def test1(self): print('TEST1') def test2(self): print('TEST2') When I run the test for this class, I got something like this: user_0 user_1 <QuerySet [<User: user_0>, <User: user_1>]> TEST2 .user_2 user_3 <QuerySet [<User: user_2>, <User: user_3>]> TEST1 What I want to know is why the username of UserFactory is not reset to user_0 after the 1st test since the setUp method is executed before each ? -
django-rest-auth: How to send custom user in login response?
So, I implemented custom user login and registration using django-rest-auth and I'm having a problem. After login the api is sending me a response like this: But my user model looks different: class User(AbstractUser): username = None id = models.UUIDField('ID', default=uuid.uuid4, primary_key=True, editable=False) email = models.EmailField('Email Address', unique=True) name = models.CharField('Name', default=None, blank=True, null=True, max_length=255) role = models.CharField('Role', max_length=255, default='CLIENT') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email I'd like to have those fields in my response, especially the "role" field. What is wrong here -
manipulate URL in django - middleware
I have id=request.GET.get('id',None) in a middleware app which receives website.com/?id=12 in the URL and I can save it in a session , request.session['id'] =id but now I want to receive a url like this : website.com/@id How can I retrieve the data like that? -
Rendering static images from a markdown file
I am having difficulty trying to render markdown files with Django, specifically static files referenced in the markdown file. After converting the markdown file into html and injecting it into a template, I cannot get the images to appear. I have tried regex replacing the src call with proper static calls after the markdown to html conversion but it does not work. Is there a specific way this can be done? A test .md file is below with three different ways to try and load the image (markdown and html which is then regrex replaced, and hardcoded static call in the md file). All of these do not work. The image does show if the static call is in the template so it is not an issue of not finding the image file. It just seems the static call is not being engaged. The browser has the following output, <img src="{% static " images="" django_reinhardt.jpg"="" %}"="" alt="Django" title="Django" width="500"> The view to convert the md file for injection is: class MdPageView(TemplateView): md_file = "test.md" template_name = 'md_viewer/md_base.html' def get_context_data(self, **kwargs): f = open(os.path.join(os.path.join(settings.BASE_DIR,'markdown'), self.md_file)) file_content = f.read() f.close() md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite' ]) body = md.convert(file_content) ## Convert html … -
I've used ArrayAgg() django model function, it works when I use one column but now two columns. Why?
I have two models. The **Teachers** model and **Courses** model. On the Courses model, I have a foreign key referencing the primary key in the Teachers model. I want to do a **query** that picks all the teachers and for each teacher to have a list of courses they created. I want I'm getting is it just picks the course description but when I add ArrayAgg another field like ArrayAgg('coursename', 'coursedescription'), I get an error. I can solve it with raw SQL but I can't figure it with django models. I'm getting this enter code here { "id": 1, "firstname": "Andrew", "second": "Njaya", "course_teachers": [ "Fundermentals of Algebra", "Fundermentals of Algebra", "Fundermentals of Algebra" ] }, { "id": 2, "firstname": "Kevin", "second": "Odhiambo", "course_teachers": [ "Fundermentals of Algebra", "Fundermentals of Algebra" ] } What I want is or it's equivalent { "id": 1, "firstname": "Andrew", "second": "Njaya", "teacher_courses": [ {coursename:"Algebra","coursedescription":"Fundermentals of Algebra"}, {coursename:"Algebra","coursedescription":"Fundermentals of Algebra"}, {coursename:"Algebra","coursedescription":"Fundermentals of Algebra"}, ] }, { "id": 2, "firstname": "Andrew", "second": "Njaya", "teacher_courses": [ {coursename:"Algebra","coursedescription":"Fundermentals of Algebra"}, {coursename:"Algebra","coursedescription":"Fundermentals of Algebra"}, {coursename:"Algebra","coursedescription":"Fundermentals of Algebra"}, ] -
DJoser with Elastic Beanstalk API
I have a Django project where I'm using Djoser for authentication. While I run things locally all my endpoints work just fine, however, once I use the API on Elastic Beanstalk I am able to create a user, get an authentication token, but I cannot log in. It says 'authentication token not provided'. The frontend is still running locally, the same request being used, and I see the token is passed through the headers: getUserInfo: ({ commit, dispatch }, data) => { console.log(data); axios.defaults.headers = { Authorization: "Token " + state.authToken, }; axios .get( "http://elasticbeanstalk.com/auth/users/me/" ) .then((response) => { commit("SETUSERINFO", response.data); commit("SETAUTHTOKEN", data["auth_token"]); // dispatch("getFollowers"); localStorage.setItem( "auth_token", JSON.stringify(data["auth_token"]) ); dispatch("getUserTweets"); dispatch("getFollowers"); }) .catch((error) => { console.log(error); }); } -
Django admin, show images for inline models
I have 3 models class Image(models.Model): file = models.ImageField() user = models.ForeignKey(settings.AUTH_USER_MODEL) class Place(models.Model): pass class PlaceImage(models.Model): image = models.ForeignKey(Image) place = models.ForeignKey(Place, related_name='images') Below are admins for them class AdminImageWidget(forms.Widget): def render(self, name, value, attrs=None, renderer=None): print(name) # prints app_name_images-0-image print(value) # empty return '' class PlaceImageInline(admin.TabularInline): model = PlaceImage fields = ['image'] formfield_overrides = { models.ForeignKey: {'widget': AdminImageWidget} } @admin.register(Place, site=admin.site) class PlaceAdmin(admin.Admin): inlines = [PlaceImageInline] I want to show images saved in the Image 's file field. However value in the render function of AdminImageWidget is empty... -
Handle Django invalid forms on generic view with inlineformset_factory
I am straggling returning proper view for form invalid cases. Also I am seeing there is lots of duplicated similar queries (68 out of 76!). Any idea for these issues? Here are my related codes: Models class Ac(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Shift(models.Model): name = models.CharField(max_length=10) active = models.BooleanField(default=True) def __str__(self): return self.name.upper() class Team(models.Model): name = models.CharField(max_length=30, unique=True) team_type = models.CharField(max_length=3, choices=team_type, blank=True) def __str__(self): return self.name.upper() class Employee(models.Model): first_name = models.CharField(max_length=50, unique=False) last_name = models.CharField(max_length=50, unique=False) nick_name = models.CharField(max_length=100, unique=True) badge = models.IntegerField(blank=True) email = models.EmailField(max_length=100, blank=True) touch = models.CharField(max_length=30, choices=work_type, blank=True) position = models.ForeignKey(Title, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) start = models.DateField() end = models.DateField(blank=True, null=True) agency = models.ForeignKey(Agency, on_delete=models.CASCADE, blank=True) shift = models.ForeignKey(Shift, on_delete=models.CASCADE) days = models.CharField(max_length=10) #, choices=wDay notes = models.CharField(max_length=500, blank=True) def __str__(self): return self.nick_name #+' ('+self.team.name+'/ '+self.shift.name+')' class Attendance(models.Model): supervisor = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) date = models.DateField() hours = models.IntegerField(default=8) ac = models.ManyToManyField(Ac, related_name='aircrafts') remarks = models.TextField(blank=True) employee = models.ForeignKey(Employee, on_delete=models.CASCADE) attendance = models.CharField(max_length=20, choices=attn_choice, blank=True) time_added = models.DateTimeField(auto_now_add=True) time_modified = models.DateTimeField(auto_now=True) def __str__(self): return str(self.date) + " " + self.employee.nick_name def get_absolute_url(self): return reverse('attendance', kwargs={'pk': self.pk}) Forms class Attnform(ModelForm): class Meta: model = Attendance fields = ['employee', … -
Django createview with OneToOneField in model
I have defined a class in model as below class Passenger(models.Model): passenger = models.OneToOneField(User, on_delete=models.CASCADE) onride = models.BooleanField() I wanted to use it with createview as mentioned below. class PassengerCreate(CreateView): model = Passenger fields = ['username','password','onride'] But it gives me error. django.core.exceptions.FieldError: Unknown field(s) (password, username) specified for Passenger -
Django template inheritance not working for multiple app
my file structure is ---app1 ----templates -----app1 ------___.html ---app2 ----templates -----app2 ------___.html now when i created a main.html inside app1/template then added the css and js....and started the block content. next i inherited this main.html block content for every templates in app1 but when i'm trying to INCLUDE (not extend) a page from app2 which has dynamic content its not loading. this is the content of the html page in app2 {% for i in all_posts %} <p> {{i.title}}<br> {{i.body}}<br> </p> {% endfor %} and this is the page in app1 i'm trying to extend {% extends 'details/main.html' %} {% block content %} <h3>Homepage</h3> loggeg in : {{user}} **{% include 'posts/posts_list.html' %}** {% endblock %} now i dont know why if i add anything before the first line in app2 html file like [abcd] its getting rendered in app1 html file. can someone please help me. thanks -
I want to convert my Python Project into Django Project
In Python Project i had used different classes but in Django we use views.py in which we use functions. i don't know how to convert my python project into a django project. Kindly suggest/Help with something new. Thanks in Advance! -
I am trying to make a Django project in PyCharm but am having the following problem
I am trying to make a Django project. I don't know why but Pycharm does not recognize any files that i put in it like database files, excel files, etc. All the files that i tried are registered in the Files Opened in Associated Applications and they are not in the Text files or the Ignored files. There is an question mark beside the file. Can anyone help me. -
Reverse for 'completetodo' with arguments '(None,)' not found. 1 pattern(s) tried: ['todo/(?P<todo_pk>[0-9]+)/complete$'] Django
i'm trying to do a function that calls a detail from a object. The URL: path('todo/<int:todo_pk>/complete', views.completetodo, name='completetodo'), The function: def completetodo(request, todo_pk): todo = get_object_or_404(Todo, pk=todo_pk, user=request.user) if request.method == 'POST': return render (request, 'TodoList/viewtodo.html') The HTML: {% extends 'TodoList/base.html' %} {% block content %} <h1>Current Todos</h1> {% if Todos %} <ul> {% for todo in Todos %} <a href="{% url 'viewtodo' todo.pk %}"> <li> {% if todo.important %} <b> {% endif %} {{ todo.title }} {% if todo.important %} </b> {% endif %} </li> </a> {% endfor %} </ul> {% else %} <h3>Você não possui nenhum Todo.</h3> {% endif %} {% endblock %} -
Problem saving page with an extra orderable and snippet
I have some problems saving an Article page in wagtail, I have 3 classes: ArticlePageModule, ArticlePageModulePlacement and ArticlePage The error says: File "/opt/miniconda3/envs/nefodev/lib/python3.7/site-packages/django/db/models/base.py", line 1222, in full_clean raise ValidationError(errors) django.core.exceptions.ValidationError: {'title': ['This field cannot be blank.']} My intention is to have a section of dynamic articles that you can add using the snippet like this: Page with several articles (preview only). By clicking on the article send to your own article page In the wagtail admin you can manage the articles by publication dates My code (supported by this code: this) from django.db import models from wagtail.core.fields import StreamField from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel, InlinePanel from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.core.models import Page, Orderable from modelcluster.fields import ParentalKey from wagtail.snippets.models import register_snippet from wagtail.snippets.edit_handlers import SnippetChooserPanel from wagtail.images.blocks import ImageChooserBlock from wagtail.core import blocks from wagtail.contrib.routable_page.models import RoutablePageMixin, route # Create your models here. @register_snippet class ArticlePageModule(models.Model): title = models.CharField(max_length=80) subtitle = models.CharField(max_length=50) thumbImage = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) panels = [ FieldPanel('title'), FieldPanel('subtitle'), ImageChooserPanel('thumbImage') ] def __str__(self): return self.title class ArticlePageModulePlacement(Orderable, models.Model): page = ParentalKey('blog.ArticlePage', on_delete=models.CASCADE, related_name='article_module_placements') article_module = models.ForeignKey(ArticlePageModule, on_delete=models.CASCADE, related_name='+') slug = models.SlugField() panels = [ FieldPanel('slug'), SnippetChooserPanel('article_module'), ] class ArticlePage(Page, RoutablePageMixin): content = … -
Django Likes count not showing any changes in the Post
I had t write the question write, I have made a like class in the model for the posts made, so far I have reached that everything was working well but now when a new post I added there is no update although when I was progressing I worked well. Now it is just refreshing the page without adding the count. I am not sure if the problem is related to the fact that I am trying to like a post in a list of posts view, not in a single post detailed view Here is the Model: class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to=upload_design_to) title = models.CharField(max_length=100) likes = models.ManyToManyField(User, blank=True, related_name='post_likes') def __str__(self): return self.title def get_absolute_url(self): return reverse("score:post-detail", kwargs={'pk': self.pk}) def like_url(self): return reverse("score:like-toggle", kwargs={'pk': self.pk}) Here are the Views: class PostListView(ListView): model = Post template_name = "score.html" context_object_name = 'posts' class PostLikeToggle(RedirectView): def get_redirect_url(self, *args, **kwargs): pk = self.kwargs.get('pk') obj = get_object_or_404(Post, pk=pk) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated(): if user in obj.likes.all: obj.like.remove(user) else: obj.like.add(user) return url_ Here are the URLs: urlpatterns = [ path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('', PostListView.as_view(), name='score'), path('/like/', PostLikeToggle.as_view(), name='like-toggle'), path('<int:pk>/', PostDetailView.as_view(), name='post-detail'), ] Here … -
Downloading file from local folder using vue
Few hours ago I noticed that <a href='path' download></a> don't work in vue, just before I wanted to finish my project. I've searched for a solution for almost 4h, but I didn't find anything, that's why I'm here. I would like to simply download files (pdf, doc, docx) from my local folder docs on the server with vue. Here is the folder tree: |--src |--app.vue |--docs |--file.doc |--file.pdf |--file.docx So there is the Template part: <v-row justify="center"> <v-col v-for="(docs, i) in info" :key="i" cols="10" > <v-card> <v-row> <v-col cols="10" > <v-icon large>mdi-file-document-outline</v-icon> {{ docs.name }} </v-col> <v-col cols="2" > <v-row><a :href="docs.file" download><v-icon color="green" large>mdi-download</v-icon></a></v-row> </v-col> </v-row> </v-card> </v-col> </v-row> ...and the script section: import axios from 'axios' export default { data () { return { info: null, } }, mounted () { axios .get('http://localhost:8080/Project/Orders/') .then(response => {this.info = response.data.data}) .catch(error => console.log(error)) }, } I'm using axios to get data from database (id, name, file=path) with Django (backend). I'd like to download files from docs folder without Django, but if anyone thinks it would be better idea to use it I'll be greatful too. -
DNS (Google Domains) is redirecting to Port instead of the Root
Been working on this for a while and could use an assist. I think I messed up. I set up a small Django application on AWS Lightsail. During set up, the tutorial instructed me to run the server at Port 8000. I ran manage.py and everything worked fine. Next, I set up the Apache server per the AWS instructions. Everything works fine when I open http:// (insert public IP address) Since I'm no longer running the server at Port 8000, I deleted that port from the Firewall. -
Django modelformset_factory overrides old instead of adding new images
I've got a problem with modelform_factory with FileField that should simply create image instances. When rendering the formset instead of getting "clear" modelforms I get one's with "previous image" link so I suppose it overrides the old one instaead of creating new. Can anybody tell me how to get only "clear" modelforms from formset? views.py class AddProductView(TemplateView): template_name = 'panel/add_product.html' imageformset = modelformset_factory(model=Image, form=ImageForm, extra=const.IMGS_PER_PRODUCT, max_num=const.IMGS_PER_PRODUCT) def get(self, request): form = ItemForm() return render(request, self.template_name, {'form': form, 'imageformset': self.imageformset}) def post(self, request): form = ItemForm(request.POST) if form.is_valid(): item = form.save() imageformset = self.imageformset(request.POST, request.FILES) if imageformset.is_valid(): images = imageformset.save(commit=False) for image in images: image.item = item image.save() forms.py class ImageForm(forms.ModelForm): class Meta: model = Image fields = ['content'] def __init__(self, *args, **kwargs): super(ImageForm, self).__init__(*args, **kwargs) self.fields['content'].widget = forms.FileInput( attrs={'class': 'dropify', 'data-height': "300"}) models.py (only needed part) class Image(models.Model): name = models.CharField(max_length=100, blank=True, unique=True) item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='images') content = models.ImageField(upload_to=get_upload_path) template.html {% for imageform in imageformset %} {{ imageform.content }} {{ imageform.id }} {% endfor %} -
Django error app engine deploy in standard env
I'm trying to deploy a django app on google app engine using postgress, and i´m running out of ideas about what could be causing this error. Everithing up perfect, but when i'm going to authenticate into django-admin, it throws me this error. ProgrammingError at /admin/login/ relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ^ Request Method: POST Request URL: https://don-numero.uc.r.appspot.com/admin/login/?next=/admin/ Django Version: 3.0.5 Exception Type: ProgrammingError Exception Value: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ^ Exception Location: /env/lib/python3.7/site-packages/django/db/backends/utils.py in _execute, line 86 Python Executable: /env/bin/python3.7 Python Version: 3.7.7 Python Path: ['/srv', '/env/bin', '/opt/python3.7/lib/python37.zip', '/opt/python3.7/lib/python3.7', '/opt/python3.7/lib/python3.7/lib-dynload', '/env/lib/python3.7/site-packages'] Already check the db access, setting file, migrations, and everything is setup correct. Any ideas? -
How to connect bases to test in django
I want to do a quiz and I want to send it to a friend. Then I want to get his accumulated points .give me advice on how to build logic. do i need rest api? for example: **me--->my custom test me--->send test link other other--->start test and collects point server ----> send me others point** -
Django - Foreign Key Constraint Fails while updating value of username in User Model
My Model - class Teacher(models.Model): user = models.OneToOneField( User, to_field='username', on_delete=models.CASCADE) name = models.CharField(max_length=50) email = models.CharField(max_length=60, unique=True) is_verified = models.BooleanField(default=False) def __str__(self): return self.name I'm trying to edit a User object's username, and I encounter the following IntegrityError - (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (`das`.`teacher_teacher`, CONSTRAINT `teacher_teacher_user_id_85660d45_fk_auth_user_username` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`username`))') I wanted the OnetoOneField to refer to username (which is unique) for developing REST API's where the primary key for teacher would be username instead of the User model's default ID key. What I've tried: - I've tried post save receiver signals to update teacher when a User object gets saved, and it has not helped me fix the issue. - I've tried adding blank=True, null=True but it doesn't let me. Any suggestions? -
TDD/testing CSS and HTML
I am stuck at this point below: '''selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: .has-error''' I tried to find a solution related to ".has-error" in order to get one of the functional tests via TDD to pass. Anyone ever experienced being stuck with that? Am I doing something wrong or missing a very little point? Your help would be appreciated! -
Django can't login user in test with UserFactory
I have a class factory like this: class UserFactory(factory.django.DjangoModelFactory): class Meta: model = settings.AUTH_USER_MODEL username = factory.Sequence(lambda n: f'user_{n}') and in my test: class MyTestView(TestCase): def test_my_view(self): user = UserFactory(password='1234') print(User.objects.all()) print(user.password) login = self.client.login(username='user_0', password='1234') print(login) the output of this test is: # ... <QuerySet [<User: user_0>]> 1234 False # ... Why my user is not logged in ? I can see that the password is not hashed, why ? does the problem come from here ? -
Django Likes Count Not Showing in Template
I have created a like option for my Post and the count doesn't seem to appear for an unknown reason here is the model: class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to=upload_design_to) title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, blank=True, related_name='post_likes') Here is the Template: <div class= "likes"> <a href="">No.{{ instance.likes.count }}</a> </div> -
Django sqlite3 OperationalError near "WHERE": syntax error
I am trying to query an sqlite database with custom sql in django and when I run the query I get OperationalError at /production/Libre-Badge-Demo-Template/ near "WHERE": syntax error I have heard talk of django's sqlite engine being unable to insert multiple parameters but I'm not sure what to make of that. here is the query after all of the variables have been inserted ('SELECT EmployeeID, FirstName, LastName, AccessLevel FROM cardholders WHERE ' 'EmployeeID LIKE %s WHERE FirstName LIKE %s WHERE LastName LIKE %s WHERE ' 'AccessLevel LIKE %s ') and here are the parameters that get escaped by django and inserted where the %s are ['F1150101', 'Micah', 'Guttman', 'Red'] here is the traceback Environment: Request Method: POST Request URL: http://localhost:8000/production/Libre-Badge-Demo-Template/ Django Version: 3.0.5 Python Version: 3.8.2 Installed Applications: ['LibreBadge', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/micah/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/micah/.local/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) The above exception (near "WHERE": syntax error) was the direct cause of the following exception: File "/home/micah/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/micah/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = …